envshed 0.24.0 → 0.25.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 (52) hide show
  1. package/dist/agent/skill-content.d.ts +1 -1
  2. package/dist/agent/skill-content.d.ts.map +1 -1
  3. package/dist/agent/skill-content.js +13 -0
  4. package/dist/agent/skill-content.js.map +1 -1
  5. package/dist/api.d.ts +1 -0
  6. package/dist/api.d.ts.map +1 -1
  7. package/dist/api.js +10 -1
  8. package/dist/api.js.map +1 -1
  9. package/dist/client-header.test.d.ts +2 -0
  10. package/dist/client-header.test.d.ts.map +1 -0
  11. package/dist/client-header.test.js +24 -0
  12. package/dist/client-header.test.js.map +1 -0
  13. package/dist/commands/import.d.ts +2 -0
  14. package/dist/commands/import.d.ts.map +1 -1
  15. package/dist/commands/import.js +224 -73
  16. package/dist/commands/import.js.map +1 -1
  17. package/dist/commands/import.test.js +348 -350
  18. package/dist/commands/import.test.js.map +1 -1
  19. package/dist/commands/push.d.ts.map +1 -1
  20. package/dist/commands/push.js +18 -4
  21. package/dist/commands/push.js.map +1 -1
  22. package/dist/commands/push.test.js +28 -0
  23. package/dist/commands/push.test.js.map +1 -1
  24. package/dist/index.js +8 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/lib/file-import.d.ts +37 -0
  27. package/dist/lib/file-import.d.ts.map +1 -0
  28. package/dist/lib/file-import.js +54 -0
  29. package/dist/lib/file-import.js.map +1 -0
  30. package/dist/lib/file-import.test.d.ts +2 -0
  31. package/dist/lib/file-import.test.d.ts.map +1 -0
  32. package/dist/lib/file-import.test.js +46 -0
  33. package/dist/lib/file-import.test.js.map +1 -0
  34. package/dist/lib/importers/dotenv.d.ts +6 -0
  35. package/dist/lib/importers/dotenv.d.ts.map +1 -1
  36. package/dist/lib/importers/dotenv.js +29 -0
  37. package/dist/lib/importers/dotenv.js.map +1 -1
  38. package/dist/lib/importers/dotenv.test.js +10 -0
  39. package/dist/lib/importers/dotenv.test.js.map +1 -1
  40. package/dist/lib/importers/index.d.ts.map +1 -1
  41. package/dist/lib/importers/index.js +2 -1
  42. package/dist/lib/importers/index.js.map +1 -1
  43. package/dist/lib/importers/index.test.js +2 -0
  44. package/dist/lib/importers/index.test.js.map +1 -1
  45. package/dist/lib/init-import.d.ts +2 -0
  46. package/dist/lib/init-import.d.ts.map +1 -1
  47. package/dist/lib/init-import.js +5 -2
  48. package/dist/lib/init-import.js.map +1 -1
  49. package/dist/locales/en.json +40 -4
  50. package/dist/locales/es.json +40 -4
  51. package/dist/locales/pt-BR.json +40 -4
  52. package/package.json +1 -1
@@ -1,7 +1,12 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
4
  import os from "os";
5
+ /**
6
+ * `envshed import <file>` as a coding agent runs it: no terminal, output captured.
7
+ * Every secret value in these tests contains CANARY, and every test checks that no
8
+ * output line (stdout, stderr, JSON) contains it.
9
+ */
5
10
  vi.mock("../api.js", () => ({
6
11
  apiGet: vi.fn(),
7
12
  apiPut: vi.fn(),
@@ -18,376 +23,369 @@ vi.mock("../api.js", () => ({
18
23
  vi.mock("../i18n.js", () => ({
19
24
  t: (key, opts) => (opts ? `${key}:${JSON.stringify(opts)}` : key),
20
25
  }));
21
- // Use vi.hoisted to create the mock before vi.mock runs
22
- const spinnerMock = vi.hoisted(() => {
23
- const calls = {
24
- start: vi.fn(),
25
- stop: vi.fn(),
26
- succeed: vi.fn(),
27
- fail: vi.fn(),
28
- warn: vi.fn(),
29
- };
30
- const spinner = {
31
- start: (...args) => { calls.start(...args); return spinner; },
32
- stop: (...args) => { calls.stop(...args); return spinner; },
33
- succeed: (...args) => { calls.succeed(...args); return spinner; },
34
- fail: (...args) => { calls.fail(...args); return spinner; },
35
- warn: (...args) => { calls.warn(...args); return spinner; },
36
- text: "",
37
- calls,
38
- };
39
- return spinner;
26
+ const spinner = vi.hoisted(() => {
27
+ const s = { text: "" };
28
+ for (const name of ["start", "stop", "succeed", "fail", "warn", "info"])
29
+ s[name] = vi.fn(() => s);
30
+ return s;
40
31
  });
41
- vi.mock("ora", () => ({ default: () => spinnerMock }));
42
- vi.mock("inquirer", () => ({
43
- default: {
44
- prompt: vi.fn().mockResolvedValue({ shouldContinue: true }),
45
- },
46
- }));
32
+ vi.mock("ora", () => ({ default: () => spinner }));
33
+ vi.mock("inquirer", () => ({ default: { prompt: vi.fn() } }));
47
34
  vi.mock("../config.js", () => ({
48
35
  resolveOpts: vi.fn((opts) => ({
49
- org: opts.org || "my-org",
50
- project: opts.project || "my-project",
36
+ org: opts.org || "acme",
37
+ project: opts.project || "api",
51
38
  env: opts.env || "development",
52
39
  })),
53
- getOriginalCwd: vi.fn(() => "/tmp/test-import"),
40
+ getOriginalCwd: vi.fn(() => "/tmp"),
54
41
  logContext: vi.fn(),
55
42
  hasProjectConfig: vi.fn(() => true),
56
43
  }));
57
- vi.mock("../lib/importers/index.js", () => ({
58
- detectFormat: vi.fn(),
59
- parseImportFile: vi.fn(),
60
- }));
61
- vi.mock("../utils.js", () => ({
62
- checkForBreakingChanges: vi.fn(() => ({ modified: [], deleted: [] })),
63
- }));
64
- import { apiGet, apiPut } from "../api.js";
65
- import { getOriginalCwd, resolveOpts } from "../config.js";
66
- import { detectFormat, parseImportFile } from "../lib/importers/index.js";
67
- import { checkForBreakingChanges } from "../utils.js";
44
+ vi.mock("../lib/init-import.js", () => ({ gitStatus: vi.fn(() => ({ tracked: false, ignored: false, top: "/tmp" })) }));
45
+ import { apiGet, apiPut, apiPost } from "../api.js";
46
+ import { getOriginalCwd } from "../config.js";
47
+ import { gitStatus } from "../lib/init-import.js";
68
48
  import inquirer from "inquirer";
69
- describe("import command", () => {
70
- let tmpDir;
49
+ const ENV_FILE = [
50
+ "DATABASE_URL=postgres://u:CANARY_db_1@db:5432/app",
51
+ "API_KEY=CANARY_key_new_2",
52
+ "STRIPE_SECRET_KEY=sk_test_CANARY_stripe_3",
53
+ "PORT=3000",
54
+ ].join("\n");
55
+ let tmpDir;
56
+ let output;
57
+ let remote;
58
+ let envs;
59
+ const isTTY = { stdin: process.stdin.isTTY, stdout: process.stdout.isTTY };
60
+ function mockApi() {
61
+ vi.mocked(apiGet).mockImplementation(async (url) => {
62
+ if (url.startsWith("/environments/")) {
63
+ return { json: async () => ({ environments: envs.map((slug) => ({ slug, name: slug })) }) };
64
+ }
65
+ return { json: async () => ({ secrets: remote }) };
66
+ });
67
+ vi.mocked(apiPut).mockResolvedValue({ ok: true, version: 2 });
68
+ vi.mocked(apiPost).mockImplementation(async (url, body) => {
69
+ if (url.startsWith("/environments/"))
70
+ envs.push(body.name);
71
+ return {};
72
+ });
73
+ }
74
+ async function run(args) {
75
+ vi.resetModules();
76
+ const { importCommand } = await import("./import.js");
77
+ const { Command } = await import("commander");
78
+ const program = new Command();
79
+ program.exitOverride();
80
+ program.addCommand(importCommand);
81
+ let exit;
82
+ try {
83
+ await program.parseAsync(["node", "envshed", "import", ...args], { from: "node" });
84
+ }
85
+ catch (err) {
86
+ const match = /^process\.exit:(\d+)$/.exec(err.message);
87
+ if (!match)
88
+ throw err;
89
+ exit = Number(match[1]);
90
+ }
91
+ return { exit, text: output.join("\n") };
92
+ }
93
+ function writeFile(name, content) {
94
+ fs.writeFileSync(path.join(tmpDir, name), content);
95
+ return name;
96
+ }
97
+ function expectNoValues(text) {
98
+ expect(text).not.toMatch(/CANARY/);
99
+ for (const call of vi.mocked(spinner.fail).mock.calls)
100
+ expect(String(call[0])).not.toMatch(/CANARY/);
101
+ }
102
+ function written() {
103
+ return vi.mocked(apiPut).mock.calls[0]?.[1]?.secrets ?? {};
104
+ }
105
+ beforeEach(() => {
106
+ vi.clearAllMocks();
107
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "import-test-"));
108
+ vi.mocked(getOriginalCwd).mockReturnValue(tmpDir);
109
+ output = [];
110
+ const capture = (...args) => { output.push(args.map(String).join(" ")); };
111
+ vi.spyOn(console, "log").mockImplementation(capture);
112
+ vi.spyOn(console, "error").mockImplementation(capture);
113
+ vi.spyOn(process, "exit").mockImplementation(((code) => {
114
+ throw new Error(`process.exit:${code ?? 0}`);
115
+ }));
116
+ // An agent's shell: no terminal on stdin or stdout.
117
+ Object.defineProperty(process.stdin, "isTTY", { value: false, configurable: true });
118
+ Object.defineProperty(process.stdout, "isTTY", { value: false, configurable: true });
119
+ remote = {};
120
+ envs = ["development", "production"];
121
+ mockApi();
122
+ });
123
+ afterEach(() => {
124
+ Object.defineProperty(process.stdin, "isTTY", { value: isTTY.stdin, configurable: true });
125
+ Object.defineProperty(process.stdout, "isTTY", { value: isTTY.stdout, configurable: true });
126
+ vi.restoreAllMocks();
127
+ });
128
+ describe("envshed import <file>: new environment content", () => {
129
+ it("imports every key into an empty environment and prints only names", async () => {
130
+ writeFile(".env", ENV_FILE);
131
+ const { exit, text } = await run([".env"]);
132
+ expect(exit).toBeUndefined();
133
+ expect(Object.keys(written()).sort()).toEqual(["API_KEY", "DATABASE_URL", "PORT", "STRIPE_SECRET_KEY"]);
134
+ expect(text).toContain("import.importedPlan");
135
+ expect(text).toContain("DATABASE_URL");
136
+ expect(text).toContain("import.nextSteps");
137
+ expectNoValues(text);
138
+ });
139
+ it("detects JSON, YAML and CSV files", async () => {
140
+ writeFile("s.json", '{"JSON_KEY":"CANARY_json_4"}');
141
+ writeFile("s.yaml", "YAML_KEY: CANARY_yaml_5\n");
142
+ writeFile("s.csv", "key,value\nCSV_KEY,CANARY_csv_6\n");
143
+ for (const [file, key] of [["s.json", "JSON_KEY"], ["s.yaml", "YAML_KEY"], ["s.csv", "CSV_KEY"]]) {
144
+ vi.mocked(apiPut).mockClear();
145
+ const { exit, text } = await run([file, "--on-conflict", "fail"]);
146
+ expect(exit).toBeUndefined();
147
+ expect(Object.keys(written())).toEqual([key]);
148
+ expectNoValues(text);
149
+ }
150
+ });
151
+ it("does not send keys whose value is already the same", async () => {
152
+ writeFile(".env", ENV_FILE);
153
+ remote = { PORT: "3000" };
154
+ await run([".env"]);
155
+ expect(written()).not.toHaveProperty("PORT");
156
+ });
157
+ it("writes nothing when every key is unchanged", async () => {
158
+ writeFile(".env", "PORT=3000\n");
159
+ remote = { PORT: "3000" };
160
+ const { exit } = await run([".env"]);
161
+ expect(exit).toBeUndefined();
162
+ expect(apiPut).not.toHaveBeenCalled();
163
+ });
164
+ });
165
+ describe("envshed import <file>: keys that already exist with another value", () => {
71
166
  beforeEach(() => {
72
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "import-test-"));
73
- vi.mocked(getOriginalCwd).mockReturnValue(tmpDir);
74
- vi.spyOn(console, "log").mockImplementation(() => { });
75
- vi.spyOn(console, "error").mockImplementation(() => { });
76
- vi.spyOn(process, "exit").mockImplementation(() => {
77
- throw new Error("process.exit");
78
- });
79
- // Reset spinner call counts
80
- Object.values(spinnerMock.calls).forEach((fn) => fn.mockReset());
81
- // Reset resolveOpts to default (some tests override it)
82
- vi.mocked(resolveOpts).mockReturnValue({
83
- org: "my-org",
84
- project: "my-project",
85
- env: "development",
86
- });
87
- // Default mocks
88
- vi.mocked(detectFormat).mockReturnValue("env");
89
- vi.mocked(parseImportFile).mockReturnValue({ KEY: "value" });
90
- vi.mocked(apiGet).mockResolvedValue({
91
- json: () => Promise.resolve({ secrets: {} }),
92
- });
93
- vi.mocked(apiPut).mockResolvedValue({});
94
- vi.mocked(inquirer.prompt).mockResolvedValue({ shouldContinue: true });
95
- });
96
- // -------------------------------------------------------------------------
97
- // Auto-detection
98
- // -------------------------------------------------------------------------
99
- it("auto-detects .env format", async () => {
100
- const file = path.join(tmpDir, ".env");
101
- fs.writeFileSync(file, "KEY=value");
102
- vi.mocked(detectFormat).mockReturnValue("env");
103
- const { importCommand } = await import("./import.js");
104
- const { Command } = await import("commander");
105
- const program = new Command();
106
- program.addCommand(importCommand);
107
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
108
- expect(detectFormat).toHaveBeenCalledWith(file);
109
- expect(parseImportFile).toHaveBeenCalledWith("env", expect.any(String));
110
- });
111
- it("auto-detects .json format", async () => {
112
- const file = path.join(tmpDir, "secrets.json");
113
- fs.writeFileSync(file, '{"KEY":"value"}');
114
- vi.mocked(detectFormat).mockReturnValue("json");
115
- const { importCommand } = await import("./import.js");
116
- const { Command } = await import("commander");
117
- const program = new Command();
118
- program.addCommand(importCommand);
119
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
120
- expect(detectFormat).toHaveBeenCalledWith(file);
121
- expect(parseImportFile).toHaveBeenCalledWith("json", expect.any(String));
122
- });
123
- it("auto-detects .yaml format", async () => {
124
- const file = path.join(tmpDir, "secrets.yaml");
125
- fs.writeFileSync(file, "KEY: value");
126
- vi.mocked(detectFormat).mockReturnValue("yaml");
127
- const { importCommand } = await import("./import.js");
128
- const { Command } = await import("commander");
129
- const program = new Command();
130
- program.addCommand(importCommand);
131
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
132
- expect(detectFormat).toHaveBeenCalledWith(file);
133
- expect(parseImportFile).toHaveBeenCalledWith("yaml", expect.any(String));
134
- });
135
- it("auto-detects .csv format", async () => {
136
- const file = path.join(tmpDir, "secrets.csv");
137
- fs.writeFileSync(file, "key,value\nKEY,val");
138
- vi.mocked(detectFormat).mockReturnValue("csv");
139
- const { importCommand } = await import("./import.js");
140
- const { Command } = await import("commander");
141
- const program = new Command();
142
- program.addCommand(importCommand);
143
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
144
- expect(detectFormat).toHaveBeenCalledWith(file);
145
- expect(parseImportFile).toHaveBeenCalledWith("csv", expect.any(String));
146
- });
147
- // -------------------------------------------------------------------------
148
- // --format flag overrides auto-detection
149
- // -------------------------------------------------------------------------
150
- it("uses --format flag and skips detectFormat", async () => {
151
- const file = path.join(tmpDir, "secrets.txt");
152
- fs.writeFileSync(file, "KEY=value");
153
- const { importCommand } = await import("./import.js");
154
- const { Command } = await import("commander");
155
- const program = new Command();
156
- program.addCommand(importCommand);
157
- await program.parseAsync(["node", "test", "import", "--force", "--format", "env", file], { from: "node" });
158
- expect(detectFormat).not.toHaveBeenCalled();
159
- expect(parseImportFile).toHaveBeenCalledWith("env", expect.any(String));
160
- });
161
- it("exits with error for unrecognized --format value", async () => {
162
- const file = path.join(tmpDir, "secrets.txt");
163
- fs.writeFileSync(file, "KEY=value");
164
- const { importCommand } = await import("./import.js");
165
- const { Command } = await import("commander");
166
- const program = new Command();
167
- program.addCommand(importCommand);
168
- await expect(program.parseAsync(["node", "test", "import", "--force", "--format", "toml", file], { from: "node" })).rejects.toThrow("process.exit");
169
- expect(spinnerMock.calls.fail).toHaveBeenCalled();
167
+ writeFile(".env", ENV_FILE);
168
+ remote = { API_KEY: "CANARY_key_old_7", PORT: "3000" };
169
+ });
170
+ it("stops with exit 2 and writes nothing when there is no terminal and no policy", async () => {
171
+ const { exit, text } = await run([".env"]);
172
+ expect(exit).toBe(2);
170
173
  expect(apiPut).not.toHaveBeenCalled();
174
+ expect(inquirer.prompt).not.toHaveBeenCalled();
175
+ expect(text).toContain("import.conflictNeedsPolicy");
176
+ expect(text).toContain("API_KEY");
177
+ expect(text).toContain("import.conflictHint");
178
+ expectNoValues(text);
179
+ });
180
+ it("keeps the current values with --on-conflict skip", async () => {
181
+ const { exit, text } = await run([".env", "--on-conflict", "skip"]);
182
+ expect(exit).toBeUndefined();
183
+ expect(Object.keys(written()).sort()).toEqual(["DATABASE_URL", "STRIPE_SECRET_KEY"]);
184
+ expect(text).toContain("import.labelSkipped");
185
+ expectNoValues(text);
186
+ });
187
+ it("overwrites with --on-conflict overwrite", async () => {
188
+ await run([".env", "--on-conflict", "overwrite"]);
189
+ expect(Object.keys(written()).sort()).toEqual(["API_KEY", "DATABASE_URL", "STRIPE_SECRET_KEY"]);
171
190
  });
172
- // -------------------------------------------------------------------------
173
- // Conflict check — shows warning and prompts when modified keys exist
174
- // -------------------------------------------------------------------------
175
- it("shows modified keys warning and prompts when conflicts exist", async () => {
176
- const file = path.join(tmpDir, ".env");
177
- fs.writeFileSync(file, "KEY=new-value");
178
- vi.mocked(parseImportFile).mockReturnValue({ KEY: "new-value" });
179
- vi.mocked(apiGet).mockResolvedValue({
180
- json: () => Promise.resolve({ secrets: { KEY: "old-value" } }),
181
- });
182
- vi.mocked(checkForBreakingChanges).mockReturnValue({ modified: ["KEY"], deleted: [] });
183
- vi.mocked(inquirer.prompt).mockResolvedValue({ shouldContinue: true });
184
- const { importCommand } = await import("./import.js");
185
- const { Command } = await import("commander");
186
- const program = new Command();
187
- program.addCommand(importCommand);
188
- await program.parseAsync(["node", "test", "import", file], { from: "node" });
189
- expect(checkForBreakingChanges).toHaveBeenCalledWith({ KEY: "old-value" }, { KEY: "new-value" });
190
- expect(inquirer.prompt).toHaveBeenCalled();
191
- expect(apiPut).toHaveBeenCalled();
192
- });
193
- it("aborts import when user declines conflict confirmation", async () => {
194
- const file = path.join(tmpDir, ".env");
195
- fs.writeFileSync(file, "KEY=new-value");
196
- vi.mocked(parseImportFile).mockReturnValue({ KEY: "new-value" });
197
- vi.mocked(apiGet).mockResolvedValue({
198
- json: () => Promise.resolve({ secrets: { KEY: "old-value" } }),
199
- });
200
- vi.mocked(checkForBreakingChanges).mockReturnValue({ modified: ["KEY"], deleted: [] });
191
+ it("fails with exit 2 and writes nothing with --on-conflict fail", async () => {
192
+ const { exit, text } = await run([".env", "--on-conflict", "fail"]);
193
+ expect(exit).toBe(2);
194
+ expect(apiPut).not.toHaveBeenCalled();
195
+ expect(text).toContain("import.conflictFailed");
196
+ expectNoValues(text);
197
+ });
198
+ it("asks in a terminal and writes nothing when the person declines", async () => {
199
+ Object.defineProperty(process.stdin, "isTTY", { value: true, configurable: true });
200
+ Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });
201
+ const ci = process.env.CI;
202
+ delete process.env.CI;
201
203
  vi.mocked(inquirer.prompt).mockResolvedValue({ shouldContinue: false });
202
- const { importCommand } = await import("./import.js");
203
- const { Command } = await import("commander");
204
- const program = new Command();
205
- program.addCommand(importCommand);
206
- await expect(program.parseAsync(["node", "test", "import", file], { from: "node" })).rejects.toThrow("process.exit");
204
+ try {
205
+ const { exit, text } = await run([".env"]);
206
+ expect(inquirer.prompt).toHaveBeenCalledTimes(1);
207
+ expect(exit).toBe(0);
208
+ expect(apiPut).not.toHaveBeenCalled();
209
+ expectNoValues(text);
210
+ }
211
+ finally {
212
+ if (ci !== undefined)
213
+ process.env.CI = ci;
214
+ }
215
+ });
216
+ it("rejects an unknown policy", async () => {
217
+ const { exit, text } = await run([".env", "--on-conflict", "merge"]);
218
+ expect(exit).toBe(1);
219
+ expect(text).toContain("import.badPolicy");
207
220
  expect(apiPut).not.toHaveBeenCalled();
208
221
  });
209
- it("skips conflict check and prompt when no keys are modified", async () => {
210
- const file = path.join(tmpDir, ".env");
211
- fs.writeFileSync(file, "KEY=same-value");
212
- vi.mocked(parseImportFile).mockReturnValue({ KEY: "same-value" });
213
- vi.mocked(apiGet).mockResolvedValue({
214
- json: () => Promise.resolve({ secrets: { KEY: "same-value" } }),
215
- });
216
- vi.mocked(checkForBreakingChanges).mockReturnValue({ modified: [], deleted: [] });
217
- const { importCommand } = await import("./import.js");
218
- const { Command } = await import("commander");
219
- const program = new Command();
220
- program.addCommand(importCommand);
221
- await program.parseAsync(["node", "test", "import", file], { from: "node" });
222
- expect(inquirer.prompt).not.toHaveBeenCalled();
223
- expect(apiPut).toHaveBeenCalled();
224
- });
225
- // -------------------------------------------------------------------------
226
- // --force flag — skips conflict check entirely
227
- // -------------------------------------------------------------------------
228
- it("skips apiGet conflict check when --force is passed", async () => {
229
- const file = path.join(tmpDir, ".env");
230
- fs.writeFileSync(file, "KEY=value");
231
- const { importCommand } = await import("./import.js");
232
- const { Command } = await import("commander");
233
- const program = new Command();
234
- program.addCommand(importCommand);
235
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
236
- expect(apiGet).not.toHaveBeenCalled();
237
- expect(checkForBreakingChanges).not.toHaveBeenCalled();
238
- expect(inquirer.prompt).not.toHaveBeenCalled();
239
- expect(apiPut).toHaveBeenCalled();
240
- });
241
- it("prints force warning when --force is used", async () => {
242
- const file = path.join(tmpDir, ".env");
243
- fs.writeFileSync(file, "KEY=value");
244
- const { importCommand } = await import("./import.js");
245
- const { Command } = await import("commander");
246
- const program = new Command();
247
- program.addCommand(importCommand);
248
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
249
- expect(console.error).toHaveBeenCalledWith(expect.stringContaining("import.forceWarning"));
250
- });
251
- // -------------------------------------------------------------------------
252
- // File not found
253
- // -------------------------------------------------------------------------
254
- it("exits with error when file does not exist", async () => {
255
- const { importCommand } = await import("./import.js");
256
- const { Command } = await import("commander");
257
- const program = new Command();
258
- program.addCommand(importCommand);
259
- await expect(program.parseAsync(["node", "test", "import", "--force", path.join(tmpDir, "nonexistent.env")], { from: "node" })).rejects.toThrow("process.exit");
260
- expect(spinnerMock.calls.fail).toHaveBeenCalled();
222
+ });
223
+ describe("envshed import <file> --dry-run", () => {
224
+ it("prints the plan with key names and writes nothing", async () => {
225
+ writeFile(".env", ENV_FILE);
226
+ remote = { API_KEY: "CANARY_key_old_7", PORT: "3000" };
227
+ const { exit, text } = await run([".env", "--dry-run"]);
228
+ expect(exit).toBeUndefined();
261
229
  expect(apiPut).not.toHaveBeenCalled();
230
+ expect(apiPost).not.toHaveBeenCalled();
231
+ expect(text).toContain("import.dryRunTitle");
232
+ expect(text).toContain("import.labelChangedOverwrite");
233
+ expect(text).toContain("import.dryRunNeedsPolicy");
234
+ expect(text).toContain("import.dryRunNothingWritten");
235
+ expectNoValues(text);
262
236
  });
263
- // -------------------------------------------------------------------------
264
- // Empty file — no secrets to import
265
- // -------------------------------------------------------------------------
266
- it("warns and returns early when file has no secrets", async () => {
267
- const file = path.join(tmpDir, ".env");
268
- fs.writeFileSync(file, "# only a comment\n");
269
- vi.mocked(parseImportFile).mockReturnValue({});
270
- const { importCommand } = await import("./import.js");
271
- const { Command } = await import("commander");
272
- const program = new Command();
273
- program.addCommand(importCommand);
274
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
275
- expect(spinnerMock.calls.warn).toHaveBeenCalledWith(expect.stringContaining("import.noSecrets"));
237
+ it("does not create a missing environment", async () => {
238
+ writeFile(".env", ENV_FILE);
239
+ const { exit, text } = await run([".env", "-e", "qa", "--create-env", "--dry-run"]);
240
+ expect(exit).toBeUndefined();
241
+ expect(apiPost).not.toHaveBeenCalled();
276
242
  expect(apiPut).not.toHaveBeenCalled();
243
+ expect(text).toContain("import.dryRunCreatesEnv");
277
244
  });
278
- // -------------------------------------------------------------------------
279
- // Successful import — calls apiPut and shows summary counts
280
- // -------------------------------------------------------------------------
281
- it("calls apiPut with parsed secrets", async () => {
282
- const file = path.join(tmpDir, ".env");
283
- fs.writeFileSync(file, "DB=postgres://localhost\nSECRET=abc");
284
- vi.mocked(parseImportFile).mockReturnValue({
285
- DB: "postgres://localhost",
286
- SECRET: "abc",
287
- });
288
- const { importCommand } = await import("./import.js");
289
- const { Command } = await import("commander");
290
- const program = new Command();
291
- program.addCommand(importCommand);
292
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
293
- expect(apiPut).toHaveBeenCalledWith("/secrets/my-org/my-project/development", { secrets: { DB: "postgres://localhost", SECRET: "abc" } });
294
- });
295
- it("shows success with new/modified/unchanged counts in summary", async () => {
296
- const file = path.join(tmpDir, ".env");
297
- fs.writeFileSync(file, "NEW=added\nEXISTING=changed\nSAME=same");
298
- vi.mocked(parseImportFile).mockReturnValue({
299
- NEW: "added",
300
- EXISTING: "changed",
301
- SAME: "same",
302
- });
303
- // Conflict check skipped via --force, existingSecrets stays {}
304
- // So all 3 keys are "new", none are modified or unchanged
305
- const { importCommand } = await import("./import.js");
306
- const { Command } = await import("commander");
307
- const program = new Command();
308
- program.addCommand(importCommand);
309
- await program.parseAsync(["node", "test", "import", "--force", file], { from: "node" });
310
- expect(spinnerMock.calls.succeed).toHaveBeenCalledWith(expect.stringContaining("import.imported"));
311
- });
312
- it("shows correct new/modified/unchanged counts when remote has existing secrets", async () => {
313
- const file = path.join(tmpDir, ".env");
314
- fs.writeFileSync(file, "NEW=added\nEXISTING=changed\nSAME=same");
315
- vi.mocked(parseImportFile).mockReturnValue({
316
- NEW: "added",
317
- EXISTING: "changed",
318
- SAME: "same",
319
- });
320
- vi.mocked(apiGet).mockResolvedValue({
321
- json: () => Promise.resolve({ secrets: { EXISTING: "old-value", SAME: "same" } }),
322
- });
323
- vi.mocked(checkForBreakingChanges).mockReturnValue({ modified: ["EXISTING"], deleted: [] });
324
- const { importCommand } = await import("./import.js");
325
- const { Command } = await import("commander");
326
- const program = new Command();
327
- program.addCommand(importCommand);
328
- await program.parseAsync(["node", "test", "import", file], { from: "node" });
329
- // succeed called with summary containing counts: total=3, new=1, modified=1, unchanged=1
330
- expect(spinnerMock.calls.succeed).toHaveBeenCalledWith(expect.stringContaining(JSON.stringify({ total: 3, target: "my-org/my-project/development", new: 1, modified: 1, unchanged: 1 })));
331
- });
332
- // -------------------------------------------------------------------------
333
- // Missing org/project/env
334
- // -------------------------------------------------------------------------
335
- it("exits when org/project/env are missing", async () => {
336
- vi.mocked(resolveOpts).mockReturnValue({
337
- org: undefined,
338
- project: undefined,
339
- env: undefined,
340
- });
341
- const file = path.join(tmpDir, ".env");
342
- fs.writeFileSync(file, "KEY=value");
343
- const { importCommand } = await import("./import.js");
344
- const { Command } = await import("commander");
345
- const program = new Command();
346
- program.addCommand(importCommand);
347
- await expect(program.parseAsync(["node", "test", "import", "--force", file], { from: "node" })).rejects.toThrow("process.exit");
348
- expect(console.error).toHaveBeenCalledWith(expect.stringContaining("common.missingOrgProjectEnv"));
349
- });
350
- // -------------------------------------------------------------------------
351
- // API errors
352
- // -------------------------------------------------------------------------
353
- it("exits with error when apiGet fails during conflict check", async () => {
354
- const file = path.join(tmpDir, ".env");
355
- fs.writeFileSync(file, "KEY=value");
356
- vi.mocked(apiGet).mockRejectedValue(new Error("Network error"));
357
- const { importCommand } = await import("./import.js");
358
- const { Command } = await import("commander");
359
- const program = new Command();
360
- program.addCommand(importCommand);
361
- await expect(program.parseAsync(["node", "test", "import", file], { from: "node" })).rejects.toThrow("process.exit");
362
- expect(spinnerMock.calls.fail).toHaveBeenCalled();
245
+ it("cannot be combined with --force", async () => {
246
+ writeFile(".env", ENV_FILE);
247
+ const { exit } = await run([".env", "--dry-run", "--force"]);
248
+ expect(exit).toBe(1);
363
249
  expect(apiPut).not.toHaveBeenCalled();
364
250
  });
365
- it("exits with error when apiPut fails", async () => {
366
- const file = path.join(tmpDir, ".env");
367
- fs.writeFileSync(file, "KEY=value");
368
- vi.mocked(apiPut).mockRejectedValue(new Error("Server error"));
369
- const { importCommand } = await import("./import.js");
370
- const { Command } = await import("commander");
371
- const program = new Command();
372
- program.addCommand(importCommand);
373
- await expect(program.parseAsync(["node", "test", "import", "--force", file], { from: "node" })).rejects.toThrow("process.exit");
374
- expect(spinnerMock.calls.fail).toHaveBeenCalledWith(expect.stringContaining("import.importFailed"));
375
- });
376
- // -------------------------------------------------------------------------
377
- // detectFormat failure (unknown extension)
378
- // -------------------------------------------------------------------------
379
- it("exits when format cannot be auto-detected", async () => {
380
- const file = path.join(tmpDir, "secrets.toml");
381
- fs.writeFileSync(file, "[section]\nKEY = 'value'");
382
- vi.mocked(detectFormat).mockImplementation(() => {
383
- throw new Error("Cannot detect format");
384
- });
385
- const { importCommand } = await import("./import.js");
386
- const { Command } = await import("commander");
387
- const program = new Command();
388
- program.addCommand(importCommand);
389
- await expect(program.parseAsync(["node", "test", "import", "--force", file], { from: "node" })).rejects.toThrow("process.exit");
390
- expect(spinnerMock.calls.fail).toHaveBeenCalled();
251
+ });
252
+ describe("envshed import <file> --output json", () => {
253
+ it("prints one JSON document with key names and no values", async () => {
254
+ writeFile(".env", ENV_FILE);
255
+ remote = { API_KEY: "CANARY_key_old_7" };
256
+ const { exit, text } = await run([".env", "--on-conflict", "skip", "--output", "json"]);
257
+ expect(exit).toBeUndefined();
258
+ const doc = JSON.parse(text);
259
+ expect(doc.target).toEqual({ org: "acme", project: "api", env: "development" });
260
+ expect(doc.keys.new).toEqual(["DATABASE_URL", "PORT", "STRIPE_SECRET_KEY"]);
261
+ expect(doc.keys.changed).toEqual(["API_KEY"]);
262
+ expect(doc.keys.skipped).toEqual(["API_KEY"]);
263
+ expect(doc.keys.written).toEqual(["DATABASE_URL", "PORT", "STRIPE_SECRET_KEY"]);
264
+ expect(doc.git).toEqual({ tracked: false, ignored: false });
265
+ expectNoValues(text);
266
+ });
267
+ it("reports a conflict as JSON with exit 2", async () => {
268
+ writeFile(".env", ENV_FILE);
269
+ remote = { API_KEY: "CANARY_key_old_7" };
270
+ const { exit, text } = await run([".env", "--output", "json"]);
271
+ expect(exit).toBe(2);
272
+ expect(JSON.parse(text)).toEqual({ error: "conflict", message: expect.any(String), keys: ["API_KEY"] });
273
+ expectNoValues(text);
274
+ });
275
+ it("reports the git state of the file", async () => {
276
+ vi.mocked(gitStatus).mockReturnValue({ tracked: true, ignored: false, top: tmpDir });
277
+ writeFile(".env", ENV_FILE);
278
+ const { text } = await run([".env", "--output", "json"]);
279
+ expect(JSON.parse(text).git).toEqual({ tracked: true, ignored: false });
280
+ });
281
+ });
282
+ describe("envshed import <file>: environments", () => {
283
+ it("names the missing environment instead of failing with a 403 from the write", async () => {
284
+ writeFile(".env", ENV_FILE);
285
+ const { exit, text } = await run([".env", "-e", "qa"]);
286
+ expect(exit).toBe(1);
287
+ expect(text).toContain("import.envNotFound");
288
+ expect(apiPut).not.toHaveBeenCalled();
289
+ });
290
+ it("creates the environment with --create-env", async () => {
291
+ writeFile(".env", ENV_FILE);
292
+ const { exit } = await run([".env", "-e", "qa", "--create-env"]);
293
+ expect(exit).toBeUndefined();
294
+ expect(apiPost).toHaveBeenCalledWith("/environments/acme/api", { name: "qa" });
295
+ expect(vi.mocked(apiPut).mock.calls[0][0]).toBe("/secrets/acme/api/qa");
296
+ });
297
+ });
298
+ describe("envshed import <file>: errors never show values", () => {
299
+ it("YAML parse errors keep only the line number", async () => {
300
+ writeFile("bad.yaml", "KEY: [CANARY_yaml_8\n");
301
+ const { exit, text } = await run(["bad.yaml"]);
302
+ expect(exit).toBe(1);
303
+ expect(text).toMatch(/import\.parseFailed(Line|Safe)/);
304
+ expectNoValues(text);
305
+ });
306
+ it("JSON parse errors do not quote the file", async () => {
307
+ writeFile("bad.json", '{"KEY": CANARY_json_9}');
308
+ const { exit, text } = await run(["bad.json"]);
309
+ expect(exit).toBe(1);
310
+ expectNoValues(text);
311
+ });
312
+ it("CSV parse errors do not quote the file", async () => {
313
+ writeFile("bad.csv", 'key,value\nKEY,"CANARY_csv_10\n');
314
+ const { exit, text } = await run(["bad.csv"]);
315
+ expect(exit).toBe(1);
316
+ expectNoValues(text);
317
+ });
318
+ it("an API error is reported without values", async () => {
319
+ writeFile(".env", ENV_FILE);
320
+ vi.mocked(apiPut).mockRejectedValue(new Error("Request failed (403)"));
321
+ const { exit, text } = await run([".env"]);
322
+ expect(exit).toBe(1);
323
+ expect(text).toContain("import.importFailed");
324
+ expectNoValues(text);
325
+ });
326
+ it("names invalid keys before writing, and hides names that look like values", async () => {
327
+ writeFile("s.json", '{"MY-KEY":"CANARY_a","GOOD":"CANARY_b","sk_live CANARY_c":"x"}');
328
+ const { exit, text } = await run(["s.json"]);
329
+ expect(exit).toBe(1);
330
+ expect(apiPut).not.toHaveBeenCalled();
331
+ expect(text).toContain("import.invalidKeys");
332
+ expect(text).toContain("MY-KEY");
333
+ expectNoValues(text);
334
+ });
335
+ it("reports skipped .env lines by number, in text and JSON, without their content", async () => {
336
+ writeFile(".env", "GOOD=CANARY_g\nisto nao e uma linha CANARY_line\nOTHER=CANARY_o\n");
337
+ const { exit, text } = await run([".env", "--on-conflict", "skip", "--output", "json"]);
338
+ expect(exit).toBeUndefined();
339
+ expect(text).toContain("import.ignoredLines");
340
+ // stderr carries the warning; stdout carries only the JSON document.
341
+ const doc = JSON.parse(output.find((line) => line.startsWith("{\n")));
342
+ expect(doc.ignoredLines).toEqual([2]);
343
+ expect(doc.keys.written).toEqual(["GOOD", "OTHER"]);
344
+ expectNoValues(text);
345
+ });
346
+ it("a missing file exits 1", async () => {
347
+ const { exit, text } = await run(["nope.env"]);
348
+ expect(exit).toBe(1);
349
+ expect(text).toContain("import.fileNotFound");
350
+ });
351
+ it("an unknown --format exits 1", async () => {
352
+ writeFile("x.env", ENV_FILE);
353
+ const { exit, text } = await run(["x.env", "--format", "toml"]);
354
+ expect(exit).toBe(1);
355
+ expect(text).toContain("import.detectFailed");
356
+ });
357
+ it("a file with no keys writes nothing", async () => {
358
+ writeFile(".env", "# only a comment\n");
359
+ const { exit } = await run([".env"]);
360
+ expect(exit).toBeUndefined();
361
+ expect(apiPut).not.toHaveBeenCalled();
362
+ });
363
+ it("exits when org, project or env cannot be resolved", async () => {
364
+ const { resolveOpts, hasProjectConfig } = await import("../config.js");
365
+ vi.mocked(resolveOpts).mockReturnValueOnce({ org: undefined, project: undefined, env: undefined });
366
+ vi.mocked(hasProjectConfig).mockReturnValueOnce(false);
367
+ writeFile(".env", ENV_FILE);
368
+ const { exit, text } = await run([".env"]);
369
+ expect(exit).toBe(1);
370
+ expect(text).toContain("common.noProjectConfig");
371
+ });
372
+ });
373
+ describe("envshed import <file> --force", () => {
374
+ it("writes every key without reading the environment", async () => {
375
+ writeFile(".env", ENV_FILE);
376
+ const { exit, text } = await run([".env", "--force"]);
377
+ expect(exit).toBeUndefined();
378
+ expect(vi.mocked(apiGet).mock.calls.some(([url]) => url.startsWith("/secrets/"))).toBe(false);
379
+ expect(Object.keys(written()).sort()).toEqual(["API_KEY", "DATABASE_URL", "PORT", "STRIPE_SECRET_KEY"]);
380
+ expect(text).toContain("import.forceWarning");
381
+ expect(text).toContain("import.importedForce");
382
+ expectNoValues(text);
383
+ });
384
+ it("cannot be combined with --on-conflict", async () => {
385
+ writeFile(".env", ENV_FILE);
386
+ const { exit, text } = await run([".env", "--force", "--on-conflict", "skip"]);
387
+ expect(exit).toBe(1);
388
+ expect(text).toContain("import.forceWithPolicy");
391
389
  expect(apiPut).not.toHaveBeenCalled();
392
390
  });
393
391
  });