better-env 0.0.7 → 0.1.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 (36) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +236 -1
  3. package/dist/adapters/cloudflare.d.ts +9 -0
  4. package/dist/adapters/cloudflare.js +175 -0
  5. package/dist/adapters/cloudflare.js.map +1 -0
  6. package/dist/adapters/netlify.d.ts +10 -0
  7. package/dist/adapters/netlify.js +176 -0
  8. package/dist/adapters/netlify.js.map +1 -0
  9. package/dist/adapters/railway.d.ts +11 -0
  10. package/dist/adapters/railway.js +234 -0
  11. package/dist/adapters/railway.js.map +1 -0
  12. package/dist/adapters/vercel.d.ts +10 -0
  13. package/dist/adapters/vercel.js +166 -0
  14. package/dist/adapters/vercel.js.map +1 -0
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +837 -0
  17. package/dist/cli.js.map +1 -0
  18. package/dist/config-schema/index.d.ts +167 -0
  19. package/dist/config-schema/index.js +205 -0
  20. package/dist/config-schema/index.js.map +1 -0
  21. package/dist/index.d.ts +12 -2
  22. package/dist/index.js +1144 -23
  23. package/dist/index.js.map +1 -1
  24. package/dist/types-BNNcKNtr.d.ts +95 -0
  25. package/dist/validate-env/index.d.ts +18 -0
  26. package/dist/validate-env/index.js +220 -0
  27. package/dist/validate-env/index.js.map +1 -0
  28. package/package.json +39 -41
  29. package/skills/better-env/SKILL.md +59 -0
  30. package/skills/better-env/agents/openai.yaml +7 -0
  31. package/skills/better-env/references/cli.md +116 -0
  32. package/skills/better-env/references/config-schema.md +77 -0
  33. package/skills/better-env/references/config.md +65 -0
  34. package/skills/better-env/references/env-validation.md +41 -0
  35. package/skills/better-env/references/runtime.md +36 -0
  36. package/skills/better-env/references/vercel-adapter.md +48 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Support. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Andre Landgraf
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1 +1,236 @@
1
- # `cli`
1
+ # better-env
2
+
3
+ `better-env` is a toolkit for environment and runtime configuration management, including `config-schema` for typed env declarations, a CLI for remote variable operations, and provider adapters to sync local dotenv files with hosted platforms (Vercel, Netlify, Railway and Cloudflare).
4
+
5
+ ## Introduction
6
+
7
+ Don't you hate it when your production build fails because you forgot to upload a new env var to your hosting provider? Isn't it super furstrating when your on another machine and you want to work on your app only to realize your env variables are not up to date or missing? I think we deserve a better way. Enter `better-env`.
8
+
9
+ - **Config schema** for full type safety for both public and server-only env variables
10
+ - **CLI** for managing and validatingyour enviorment variables
11
+ - **Adapters** to keep local variables in sync with remote providers (Vercel, Netlify, Cloudflare, etc.)
12
+
13
+ ## Setup
14
+
15
+ ### 1) Install the coding agent skill
16
+
17
+ Install the `better-env` skill first so coding agents can apply the recommended conventions and workflows:
18
+
19
+ ```bash
20
+ npx skills add neondatabase/better-env
21
+ ```
22
+
23
+ ### 2) Add typed config modules for environment variables
24
+
25
+ Use `better-env/config-schema` to define typed config objects. This gives runtime validation and typed access for both server and public values.
26
+
27
+ ```ts
28
+ import { configSchema, server, pub } from "better-env/config-schema";
29
+
30
+ export const sentryConfig = configSchema(
31
+ "Sentry",
32
+ {
33
+ token: server({ env: "SENTRY_AUTH_TOKEN" }),
34
+ dsn: pub({
35
+ env: "NEXT_PUBLIC_SENTRY_DSN",
36
+ value: process.env.NEXT_PUBLIC_SENTRY_DSN,
37
+ }),
38
+ },
39
+ {
40
+ flag: {
41
+ env: "NEXT_PUBLIC_ENABLE_SENTRY",
42
+ value: process.env.NEXT_PUBLIC_ENABLE_SENTRY,
43
+ },
44
+ },
45
+ );
46
+ ```
47
+
48
+ Best practice: keep one `config.ts` per feature or infrastructure service.
49
+
50
+ - `src/lib/auth/config.ts`
51
+ - `src/lib/database/config.ts`
52
+ - `src/lib/sentry/config.ts`
53
+
54
+ This keeps ownership clear and allows validation to discover config declarations consistently.
55
+
56
+ ### 3) Add and run environment validation
57
+
58
+ If your project follows the `config.ts` convention, you can use the `better-env validate` command to validate your current app enviornment against your application's config schemas.
59
+
60
+ ```json
61
+ {
62
+ "scripts": {
63
+ "env:validate": "better-env validate --environment development",
64
+ "dev": "npm run env:validate && next dev",
65
+ "build": "better-env validate --environment production && next build"
66
+ }
67
+ }
68
+ ```
69
+
70
+ ## Remote Environment Management
71
+
72
+ If you're using a supported hosting provider, you can use the `better-env` CLI to manage your remote environment variables and keep your local dotenv files in sync.
73
+
74
+ ### Requirements
75
+
76
+ - Provider CLI available in `$PATH`
77
+ - Vercel adapter: `vercel` (or set `vercelBin`)
78
+ - Netlify adapter: `netlify` (or set `netlifyBin`)
79
+ - Railway adapter: `railway` (or set `railwayBin`)
80
+ - Cloudflare adapter: `wrangler` (or set `wranglerBin`)
81
+
82
+ ### Configure `better-env.ts`
83
+
84
+ Create `better-env.ts` in your project root:
85
+
86
+ ```ts
87
+ import { defineBetterEnv, vercelAdapter } from "better-env";
88
+
89
+ export default defineBetterEnv({
90
+ adapter: vercelAdapter(),
91
+ });
92
+ ```
93
+
94
+ Netlify example:
95
+
96
+ ```ts
97
+ import { defineBetterEnv, netlifyAdapter } from "better-env";
98
+
99
+ export default defineBetterEnv({
100
+ adapter: netlifyAdapter(),
101
+ });
102
+ ```
103
+
104
+ Cloudflare Workers example:
105
+
106
+ ```ts
107
+ import { cloudflareAdapter, defineBetterEnv } from "better-env";
108
+
109
+ export default defineBetterEnv({
110
+ adapter: cloudflareAdapter(),
111
+ });
112
+ ```
113
+
114
+ Railway example:
115
+
116
+ ```ts
117
+ import { defineBetterEnv, railwayAdapter } from "better-env";
118
+
119
+ export default defineBetterEnv({
120
+ adapter: railwayAdapter(),
121
+ });
122
+ ```
123
+
124
+ Run initial setup and first sync:
125
+
126
+ ```bash
127
+ npx better-env init
128
+ npx better-env pull --environment development
129
+ ```
130
+
131
+ ## Environments
132
+
133
+ By default, `better-env` provides these environment names:
134
+
135
+ - `development` → writes `.env.development`, pulls from Vercel `development`
136
+ - `preview` → writes `.env.preview`, pulls from Vercel `preview`
137
+ - `production` → writes `.env.production`, pulls from Vercel `production`
138
+ - `test` → writes `.env.test`, local-only (no remote mapping)
139
+ - `local` → writes `.env.local`, local-only (no remote mapping)
140
+
141
+ For Netlify adapter, the same local names map to:
142
+
143
+ - `development` → Netlify `dev`
144
+ - `preview` → Netlify `deploy-preview`
145
+ - `production` → Netlify `production`
146
+ - `test` → local-only (no remote mapping)
147
+
148
+ For Cloudflare adapter, the same local names map to Workers environments:
149
+
150
+ - `development` → Wrangler `--env development`
151
+ - `preview` → Wrangler `--env preview`
152
+ - `production` → Wrangler default environment (no `--env` flag)
153
+ - `test` → local-only (no remote mapping)
154
+
155
+ For Railway adapter, the same local names map to Railway environments by name:
156
+
157
+ - `development` → Railway `development`
158
+ - `preview` → Railway `preview`
159
+ - `production` → Railway `production`
160
+ - `test` → local-only (no remote mapping)
161
+
162
+ You can override (or add) environments in `better-env.ts`:
163
+
164
+ ```ts
165
+ import { defineBetterEnv, vercelAdapter } from "better-env";
166
+
167
+ export default defineBetterEnv({
168
+ adapter: vercelAdapter(),
169
+ environments: {
170
+ development: { envFile: ".env.development", remote: "development" },
171
+ preview: { envFile: ".env.preview", remote: "preview" },
172
+ production: { envFile: ".env.production", remote: "production" },
173
+ test: { envFile: ".env.test", remote: null },
174
+ },
175
+ });
176
+ ```
177
+
178
+ Notes: `better-env` never writes to `.env.local` (use it as your local override).
179
+
180
+ ### Cloudflare + better-env
181
+
182
+ - `better-env pull` is not supported for Cloudflare secrets (Wrangler cannot read back secret values).
183
+ - `wrangler dev` (local mode) does not inject remote secrets into local dotenv files so it's on you to keep your local env vars in sync with the remote environment. Or run `wrangler dev --remote` to use deployed environment bindings at runtime.
184
+ - Recommended workflow: keep local files (`.env.*` / `.dev.vars`) as source of truth, then push with `better-env load`.
185
+
186
+ ## CLI Command Reference
187
+
188
+ - `init`: validates provider CLI availability and verifies project linkage when required (`.vercel/project.json` or `.netlify/state.json`)
189
+ - `pull`: fetches remote variables and ensures local `.gitignore` coverage
190
+ - `validate`: validates required variables by loading `config.ts` modules
191
+ - `add|upsert|update|delete`: applies single-variable mutations to the remote provider
192
+ - `load`: applies dotenv file contents using `add|update|upsert|replace` modes
193
+ - `environments list`: prints configured local/remote environment mappings
194
+
195
+ ```bash
196
+ better-env init [--yes]
197
+ better-env pull [--environment <name>]
198
+ better-env validate [--environment <name>]
199
+
200
+ better-env add <key> <value> [--environment <name>] [--sensitive]
201
+ better-env upsert <key> <value> [--environment <name>] [--sensitive]
202
+ better-env update <key> <value> [--environment <name>] [--sensitive]
203
+ better-env delete <key> [--environment <name>]
204
+
205
+ better-env load <file> [--environment <name>] [--mode add|update|upsert|replace] [--sensitive]
206
+ better-env environments list
207
+ ```
208
+
209
+ ## Contribution
210
+
211
+ Run local checks:
212
+
213
+ ```bash
214
+ npm run build
215
+ npm run typecheck
216
+ npm test
217
+ ```
218
+
219
+ Run adapter e2e coverage:
220
+
221
+ - Live Vercel adapter test (creates and removes a real project):
222
+ - Requires authenticated `vercel` CLI and project create/remove permissions
223
+ - Run with `npm run test:e2e:vercel`
224
+ - Live Netlify adapter test (creates and removes a real project):
225
+ - Requires authenticated `netlify` CLI and project create/remove permissions
226
+ - Run with `npm run test:e2e:netlify`
227
+ - Live Railway adapter test (creates and removes a real project):
228
+ - Requires authenticated `railway` CLI and project create/remove permissions
229
+ - Optionally set `BETTER_ENV_RAILWAY_WORKSPACE=<workspace-id>` when multiple workspaces exist
230
+ - Run with `npm run test:e2e:railway`
231
+ - Netlify adapter runtime e2e test (fake CLI binary):
232
+ - Run with `bun test test/e2e/runtime-netlify.test.ts`
233
+ - Railway adapter runtime e2e test (fake CLI binary):
234
+ - Run with `npm run test:e2e:railway:runtime`
235
+ - Cloudflare adapter runtime e2e test:
236
+ - Run with `bun test test/e2e/runtime-cloudflare.test.ts`
@@ -0,0 +1,9 @@
1
+ import { a as BetterEnvAdapter } from '../types-BNNcKNtr.js';
2
+
3
+ type CloudflareAdapterOptions = {
4
+ wranglerBin?: string;
5
+ config?: string;
6
+ };
7
+ declare function cloudflareAdapter(options?: CloudflareAdapterOptions): BetterEnvAdapter;
8
+
9
+ export { type CloudflareAdapterOptions, cloudflareAdapter };
@@ -0,0 +1,175 @@
1
+ // src/lib/adapters/cloudflare.ts
2
+ function cloudflareAdapter(options = {}) {
3
+ const wranglerBin = options.wranglerBin ?? "wrangler";
4
+ const withGlobals = (args) => {
5
+ const out = [wranglerBin, ...args];
6
+ if (options.config) out.push("--config", options.config);
7
+ return out;
8
+ };
9
+ async function run(ctx, args, runOptions) {
10
+ return ctx.exec(withGlobals(args), {
11
+ cwd: ctx.projectDir,
12
+ stdin: runOptions?.stdin
13
+ });
14
+ }
15
+ async function listKeys(ctx, environment) {
16
+ const args = ["secret", "list", ...toEnvironmentArgs(environment)];
17
+ const results = await Promise.all([
18
+ run(ctx, [...args, "--format", "json"]),
19
+ run(ctx, [...args, "--json"])
20
+ ]);
21
+ for (const res of results) {
22
+ if (res.exitCode !== 0) continue;
23
+ const keys = tryParseWranglerSecretList(res.stdout);
24
+ if (keys) return keys;
25
+ }
26
+ const [formatJsonResult, jsonResult] = results;
27
+ throw new Error(
28
+ [
29
+ `Failed to list env vars from Cloudflare (${environment}).`,
30
+ formatJsonResult.stderr,
31
+ jsonResult.stderr
32
+ ].filter((line) => line.trim().length > 0).join("\n")
33
+ );
34
+ }
35
+ return {
36
+ name: "cloudflare",
37
+ defaultEnvironments() {
38
+ return {
39
+ development: { envFile: ".env.development", remote: "development" },
40
+ preview: { envFile: ".env.preview", remote: "preview" },
41
+ production: { envFile: ".env.production", remote: "production" },
42
+ test: { envFile: ".env.test", remote: null }
43
+ };
44
+ },
45
+ async init(ctx) {
46
+ const version = await run(ctx, ["--version"]);
47
+ if (version.exitCode !== 0) {
48
+ throw new Error(
49
+ `Failed to run Wrangler CLI. Is \`${wranglerBin}\` installed?
50
+ ${version.stderr}`.trim()
51
+ );
52
+ }
53
+ },
54
+ async pull(_ctx, { environment }) {
55
+ throw new Error(
56
+ [
57
+ `Cloudflare adapter cannot pull secret values for "${environment}".`,
58
+ "Wrangler does not expose secret values after upload.",
59
+ "Use local dotenv files as source of truth and push with `better-env load`."
60
+ ].join("\n")
61
+ );
62
+ },
63
+ async add(ctx, { environment, key, value, sensitive: _sensitive }) {
64
+ const exists = await envVarExists(ctx, listKeys, { environment, key });
65
+ if (exists) {
66
+ throw new Error(
67
+ `Env var ${key} already exists in ${environment}. Use \`better-env update\` or \`better-env upsert\`.`
68
+ );
69
+ }
70
+ await this.upsert(ctx, {
71
+ environment,
72
+ key,
73
+ value,
74
+ sensitive: false
75
+ });
76
+ },
77
+ async upsert(ctx, { environment, key, value, sensitive: _sensitive }) {
78
+ const res = await run(
79
+ ctx,
80
+ ["secret", "put", key, ...toEnvironmentArgs(environment)],
81
+ { stdin: `${value}
82
+ ` }
83
+ );
84
+ if (res.exitCode !== 0) {
85
+ throw new Error(
86
+ `Failed to upsert env var ${key} (${environment}).
87
+ ${res.stderr}`.trim()
88
+ );
89
+ }
90
+ },
91
+ async update(ctx, { environment, key, value, sensitive: _sensitive }) {
92
+ const exists = await envVarExists(ctx, listKeys, { environment, key });
93
+ if (!exists) {
94
+ throw new Error(
95
+ `Env var ${key} does not exist in ${environment}. Use \`better-env add\` or \`better-env upsert\`.`
96
+ );
97
+ }
98
+ await this.upsert(ctx, {
99
+ environment,
100
+ key,
101
+ value,
102
+ sensitive: false
103
+ });
104
+ },
105
+ async delete(ctx, { environment, key }) {
106
+ const res = await run(ctx, [
107
+ "secret",
108
+ "delete",
109
+ key,
110
+ ...toEnvironmentArgs(environment)
111
+ ]);
112
+ if (res.exitCode !== 0) {
113
+ throw new Error(
114
+ `Failed to delete env var ${key} (${environment}).
115
+ ${res.stderr}`.trim()
116
+ );
117
+ }
118
+ },
119
+ async listEnvironments() {
120
+ return ["development", "preview", "production"];
121
+ },
122
+ async listEnvVars(ctx, { environment }) {
123
+ return listKeys(ctx, environment);
124
+ }
125
+ };
126
+ }
127
+ async function envVarExists(ctx, listKeys, options) {
128
+ const keys = await listKeys(ctx, options.environment);
129
+ return keys.includes(options.key);
130
+ }
131
+ function toEnvironmentArgs(environment) {
132
+ if (environment === "production") return [];
133
+ return ["--env", environment];
134
+ }
135
+ function tryParseWranglerSecretList(stdout) {
136
+ const parsed = tryParseJson(stdout);
137
+ if (!Array.isArray(parsed)) return null;
138
+ const keys = /* @__PURE__ */ new Set();
139
+ for (const item of parsed) {
140
+ if (!isRecord(item)) continue;
141
+ const name = item.name;
142
+ if (isEnvVarName(name)) {
143
+ keys.add(name);
144
+ }
145
+ }
146
+ return Array.from(keys);
147
+ }
148
+ function tryParseJson(value) {
149
+ const trimmed = value.trim();
150
+ if (trimmed.length === 0) return null;
151
+ try {
152
+ return JSON.parse(trimmed);
153
+ } catch {
154
+ const start = trimmed.indexOf("[");
155
+ const end = trimmed.lastIndexOf("]");
156
+ if (start === -1 || end === -1 || start > end) return null;
157
+ const possibleJson = trimmed.slice(start, end + 1);
158
+ try {
159
+ return JSON.parse(possibleJson);
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+ }
165
+ function isRecord(value) {
166
+ return typeof value === "object" && value !== null;
167
+ }
168
+ function isEnvVarName(value) {
169
+ if (typeof value !== "string") return false;
170
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
171
+ }
172
+
173
+ export { cloudflareAdapter };
174
+ //# sourceMappingURL=cloudflare.js.map
175
+ //# sourceMappingURL=cloudflare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/lib/adapters/cloudflare.ts"],"names":[],"mappings":";AAWO,SAAS,iBAAA,CACd,OAAA,GAAoC,EAAC,EACnB;AAClB,EAAA,MAAM,WAAA,GAAc,QAAQ,WAAA,IAAe,UAAA;AAE3C,EAAA,MAAM,WAAA,GAAc,CAAC,IAAA,KAA6B;AAChD,IAAA,MAAM,GAAA,GAAM,CAAC,WAAA,EAAa,GAAG,IAAI,CAAA;AACjC,IAAA,IAAI,QAAQ,MAAA,EAAQ,GAA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,KAAA,KAAU,IAAA;AAChD;AAEA,SAAS,aAAa,KAAA,EAAiC;AACrD,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AACtC,EAAA,OAAO,0BAAA,CAA2B,KAAK,KAAK,CAAA;AAC9C","file":"cloudflare.js","sourcesContent":["import type {\n BetterEnvAdapter,\n BetterEnvAdapterContext,\n ExecResult,\n} from \"../runtime/types.ts\";\n\nexport type CloudflareAdapterOptions = {\n wranglerBin?: string;\n config?: string;\n};\n\nexport function cloudflareAdapter(\n options: CloudflareAdapterOptions = {},\n): BetterEnvAdapter {\n const wranglerBin = options.wranglerBin ?? \"wrangler\";\n\n const withGlobals = (args: string[]): string[] => {\n const out = [wranglerBin, ...args];\n if (options.config) out.push(\"--config\", options.config);\n return out;\n };\n\n async function run(\n ctx: BetterEnvAdapterContext,\n args: string[],\n runOptions?: { stdin?: string },\n ): Promise<ExecResult> {\n return ctx.exec(withGlobals(args), {\n cwd: ctx.projectDir,\n stdin: runOptions?.stdin,\n });\n }\n\n async function listKeys(\n ctx: BetterEnvAdapterContext,\n environment: string,\n ): Promise<string[]> {\n const args = [\"secret\", \"list\", ...toEnvironmentArgs(environment)];\n const results = await Promise.all([\n run(ctx, [...args, \"--format\", \"json\"]),\n run(ctx, [...args, \"--json\"]),\n ]);\n\n for (const res of results) {\n if (res.exitCode !== 0) continue;\n const keys = tryParseWranglerSecretList(res.stdout);\n if (keys) return keys;\n }\n\n const [formatJsonResult, jsonResult] = results;\n throw new Error(\n [\n `Failed to list env vars from Cloudflare (${environment}).`,\n formatJsonResult.stderr,\n jsonResult.stderr,\n ]\n .filter((line) => line.trim().length > 0)\n .join(\"\\n\"),\n );\n }\n\n return {\n name: \"cloudflare\",\n defaultEnvironments() {\n return {\n development: { envFile: \".env.development\", remote: \"development\" },\n preview: { envFile: \".env.preview\", remote: \"preview\" },\n production: { envFile: \".env.production\", remote: \"production\" },\n test: { envFile: \".env.test\", remote: null },\n };\n },\n\n async init(ctx) {\n const version = await run(ctx, [\"--version\"]);\n if (version.exitCode !== 0) {\n throw new Error(\n `Failed to run Wrangler CLI. Is \\`${wranglerBin}\\` installed?\\n${version.stderr}`.trim(),\n );\n }\n },\n\n async pull(_ctx, { environment }) {\n throw new Error(\n [\n `Cloudflare adapter cannot pull secret values for \"${environment}\".`,\n \"Wrangler does not expose secret values after upload.\",\n \"Use local dotenv files as source of truth and push with `better-env load`.\",\n ].join(\"\\n\"),\n );\n },\n\n async add(ctx, { environment, key, value, sensitive: _sensitive }) {\n const exists = await envVarExists(ctx, listKeys, { environment, key });\n if (exists) {\n throw new Error(\n `Env var ${key} already exists in ${environment}. Use \\`better-env update\\` or \\`better-env upsert\\`.`,\n );\n }\n\n await this.upsert(ctx, {\n environment,\n key,\n value,\n sensitive: false,\n });\n },\n\n async upsert(ctx, { environment, key, value, sensitive: _sensitive }) {\n const res = await run(\n ctx,\n [\"secret\", \"put\", key, ...toEnvironmentArgs(environment)],\n { stdin: `${value}\\n` },\n );\n if (res.exitCode !== 0) {\n throw new Error(\n `Failed to upsert env var ${key} (${environment}).\\n${res.stderr}`.trim(),\n );\n }\n },\n\n async update(ctx, { environment, key, value, sensitive: _sensitive }) {\n const exists = await envVarExists(ctx, listKeys, { environment, key });\n if (!exists) {\n throw new Error(\n `Env var ${key} does not exist in ${environment}. Use \\`better-env add\\` or \\`better-env upsert\\`.`,\n );\n }\n\n await this.upsert(ctx, {\n environment,\n key,\n value,\n sensitive: false,\n });\n },\n\n async delete(ctx, { environment, key }) {\n const res = await run(ctx, [\n \"secret\",\n \"delete\",\n key,\n ...toEnvironmentArgs(environment),\n ]);\n if (res.exitCode !== 0) {\n throw new Error(\n `Failed to delete env var ${key} (${environment}).\\n${res.stderr}`.trim(),\n );\n }\n },\n\n async listEnvironments() {\n return [\"development\", \"preview\", \"production\"];\n },\n\n async listEnvVars(ctx, { environment }) {\n return listKeys(ctx, environment);\n },\n };\n}\n\nasync function envVarExists(\n ctx: BetterEnvAdapterContext,\n listKeys: (\n ctx: BetterEnvAdapterContext,\n environment: string,\n ) => Promise<string[]>,\n options: { environment: string; key: string },\n): Promise<boolean> {\n const keys = await listKeys(ctx, options.environment);\n return keys.includes(options.key);\n}\n\nfunction toEnvironmentArgs(environment: string): string[] {\n if (environment === \"production\") return [];\n return [\"--env\", environment];\n}\n\nfunction tryParseWranglerSecretList(stdout: string): string[] | null {\n const parsed = tryParseJson(stdout);\n if (!Array.isArray(parsed)) return null;\n\n const keys = new Set<string>();\n for (const item of parsed) {\n if (!isRecord(item)) continue;\n const name = item.name;\n if (isEnvVarName(name)) {\n keys.add(name);\n }\n }\n\n return Array.from(keys);\n}\n\nfunction tryParseJson(value: string): unknown {\n const trimmed = value.trim();\n if (trimmed.length === 0) return null;\n\n try {\n return JSON.parse(trimmed);\n } catch {\n // Wrangler can occasionally prefix logs before JSON output.\n const start = trimmed.indexOf(\"[\");\n const end = trimmed.lastIndexOf(\"]\");\n if (start === -1 || end === -1 || start > end) return null;\n const possibleJson = trimmed.slice(start, end + 1);\n try {\n return JSON.parse(possibleJson);\n } catch {\n return null;\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isEnvVarName(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import { a as BetterEnvAdapter } from '../types-BNNcKNtr.js';
2
+
3
+ type NetlifyAdapterOptions = {
4
+ netlifyBin?: string;
5
+ authToken?: string;
6
+ filter?: string;
7
+ };
8
+ declare function netlifyAdapter(options?: NetlifyAdapterOptions): BetterEnvAdapter;
9
+
10
+ export { type NetlifyAdapterOptions, netlifyAdapter };