Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/build-output-mode-dotenv.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"cf": patch
---

Load `.env` files for the Build Output's mode when `--mode` is omitted

`cf deploy`, `cf workers versions create`, `cf workers triggers deploy`, and `cf previews deploy` now load `.env.<mode>` and `.env.<mode>.local` for the mode recorded in the Build Output when `--mode` is not passed. Previously they read only `.env` and `.env.local`, so deploying a staging build without repeating `--mode staging` could use the account and API token from `.env` instead of `.env.staging`.

Vite records its default `production` mode when a build runs without `--mode`, so these commands now also load `.env.production` for such builds, matching the files the build itself used. An explicit `--mode` must still match the recorded mode.
6 changes: 6 additions & 0 deletions packages/cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@ work. Its callback must finish, restoring the file values, before the child is
started. Do not suppress normal inheritance of values that were already
exported in the invoking environment.

Commands that consume Build Output load dotenv values with
`withBuildOutputDotEnv()` from `src/lib/build-output-dotenv.ts`. It reads the
output first and loads the files for the mode the output recorded, so deploys
read the same `.env.<mode>` files as the build. Callers must reject the
`--local` flag and validate `--mode` against the recorded mode.

Tests for these commands must show both sides of the boundary: file values are
available to the parent where required and sensitive file values are absent
when the child process starts. Update the exclusion tests whenever a command
Expand Down
68 changes: 68 additions & 0 deletions packages/cli/src/__tests__/commands/deploy/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,74 @@ describe("cf deploy", () => {
expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBeUndefined();
});

it.each([
{
name: "prebuilt output when --mode is omitted",
flags: ["--prebuilt"],
recordedMode: "staging",
buildArgv: undefined,
},
{
// Vite records its default "production" mode when --mode is omitted.
name: "a delegated build's default mode",
flags: [],
recordedMode: "production",
buildArgv: ["build"],
},
])(
"loads dotenv files for the recorded mode of $name",
async ({ flags, recordedMode, buildArgv }) => {
vi.stubEnv("CLOUDFLARE_API_TOKEN", undefined);
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined);
let uploadRequest:
| { account: string | undefined; authorization: string | null }
| undefined;
mockWorkerUpload(
{},
{
onRequest: (request) => {
uploadRequest = {
account: new URL(request.url).pathname.match(
/\/accounts\/([^/]+)\//
)?.[1],
authorization: request.headers.get("authorization"),
};
},
}
);
await seed({
".env": [
"CLOUDFLARE_API_TOKEN=default-token",
"CLOUDFLARE_ACCOUNT_ID=default-account",
Comment thread
jamesopstad marked this conversation as resolved.
Resolved
].join("\n"),
// The token is only in .env, so it must be merged with the
// mode file rather than replaced by it.
[`.env.${recordedMode}`]: `CLOUDFLARE_ACCOUNT_ID=${recordedMode}-account`,
".cloudflare/output/v1/config.json": buildOutputRootConfig({
buildContext: { isPreview: false, mode: recordedMode },
}),
".cloudflare/output/v1/workers/default/worker.config.json":
workerConfig(),
".cloudflare/output/v1/workers/default/bundle/index.js":
"export default { fetch() { return new Response('ok'); } }",
});

const { exitCode } = await runCf(["deploy", ...flags]);

expect(exitCode).toBe(0);
if (buildArgv === undefined) {
expect(buildDelegateWasCalled()).toBe(false);
} else {
expect(readBuildDelegateArgv()).toEqual(buildArgv);
}
expect(uploadRequest).toEqual({
account: `${recordedMode}-account`,
authorization: "Bearer default-token",
});
expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBeUndefined();
}
);

it("deploys a single ESM module", async () => {
const upload = mockWorkerUpload();
await seed({
Expand Down
53 changes: 53 additions & 0 deletions packages/cli/src/__tests__/commands/previews-deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,59 @@ describe("cf previews deploy", () => {
);
});

describe("dotenv mode", () => {
runInTempDir();

it("loads dotenv files for the recorded mode when --prebuilt omits --mode", async () => {
vi.stubEnv("CLOUDFLARE_API_TOKEN", undefined);
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined);
writeFileSync(
".env",
"CLOUDFLARE_API_TOKEN=default-token\nCLOUDFLARE_ACCOUNT_ID=default-account\n"
);
writeFileSync(
".env.staging",
"CLOUDFLARE_API_TOKEN=staging-token\nCLOUDFLARE_ACCOUNT_ID=staging-account\n"
);
mocks.readBuildOutput.mockResolvedValue({
rootConfig: { buildContext: { isPreview: true, mode: "staging" } },
workers: {
default: {
config: { type: "worker", name: "preview-worker" },
bundleDir: "/project/bundle",
},
},
});
mocks.assembleBuildResult.mockReturnValue({ content: "worker code" });
mocks.getAuthToken.mockImplementation(
async () => process.env.CLOUDFLARE_API_TOKEN
);
mocks.getAccountId.mockImplementation(
async () => process.env.CLOUDFLARE_ACCOUNT_ID
);
mocks.createDeployContext.mockReturnValue({
logger: { log: vi.fn(), info: vi.fn() },
});
mocks.previewBuildOutput.mockResolvedValue(previewResult);

await expect(
runPreviewDeploy({
"preview-name": "feature",
prebuilt: true,
} as Parameters<typeof runPreviewDeploy>[0])
).resolves.toBe(previewResult);

expect(mocks.createDeployContext).toHaveBeenCalledWith("staging-token");
expect(mocks.previewBuildOutput).toHaveBeenCalledWith(
"staging-account",
expect.any(Object),
expect.any(Object),
expect.any(Object)
);
expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBeUndefined();
});
});

it("deploys the Preview under CLOUDFLARE_CI_OVERRIDE_WORKER_NAME", async () => {
vi.stubEnv("CLOUDFLARE_CI_OVERRIDE_WORKER_NAME", "dashboard-worker");
const rootConfig = { buildContext: { isPreview: true } };
Expand Down
105 changes: 105 additions & 0 deletions packages/cli/src/__tests__/commands/triggers-deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,111 @@ describe("cf workers triggers deploy", () => {
expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBeUndefined();
});

describe("dotenv mode", () => {
let schedulesRequest:
| { account: unknown; authorization: string | null }
| undefined;

beforeEach(async () => {
vi.stubEnv("CLOUDFLARE_API_TOKEN", undefined);
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined);
schedulesRequest = undefined;
msw.use(
http.put(
"*/accounts/:accountId/workers/scripts/:scriptName/schedules",
({ request, params }) => {
schedulesRequest = {
account: params.accountId,
authorization: request.headers.get("authorization"),
};
return HttpResponse.json(createFetchResult({ schedules: [] }));
}
)
);
await seed({
".env": [
"CLOUDFLARE_API_TOKEN=default-token",
"CLOUDFLARE_ACCOUNT_ID=default-account",
].join("\n"),
".env.staging": [
"CLOUDFLARE_API_TOKEN=staging-token",
"CLOUDFLARE_ACCOUNT_ID=staging-account",
].join("\n"),
".cloudflare/output/v1/workers/default/worker.config.json":
workerConfig({
triggers: [{ type: "scheduled", schedule: "*/5 * * * *" }],
}),
".cloudflare/output/v1/workers/default/bundle/index.js":
"export default { fetch() { return new Response('ok'); } }",
});
});

it.each([
{
name: "the recorded mode when --mode is omitted",
recordedMode: "staging",
flags: [],
expected: "staging",
},
{
name: "an explicit --mode",
recordedMode: "staging",
flags: ["--mode", "staging"],
expected: "staging",
},
{
name: "no mode when the Build Output records none",
recordedMode: undefined,
flags: [],
expected: "default",
},
])(
"loads prebuilt dotenv files for $name",
async ({ recordedMode, flags, expected }) => {
await seed({
".cloudflare/output/v1/config.json": buildOutputRootConfig({
buildContext: { isPreview: false, mode: recordedMode },
}),
});

const { exitCode } = await runCf([
...TRIGGERS_DEPLOY_COMMAND,
"--prebuilt",
...flags,
]);

expect(exitCode).toBe(0);
expect(schedulesRequest).toEqual({
account: `${expected}-account`,
authorization: `Bearer ${expected}-token`,
});
expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBeUndefined();
}
);

it("loads dotenv files for the mode a delegated build recorded by default", async () => {
// Vite records its default "production" mode when --mode is omitted.
await seed({
".env.production": [
"CLOUDFLARE_API_TOKEN=production-token",
"CLOUDFLARE_ACCOUNT_ID=production-account",
].join("\n"),
".cloudflare/output/v1/config.json": buildOutputRootConfig({
buildContext: { isPreview: false, mode: "production" },
}),
});

const { exitCode } = await runCf(TRIGGERS_DEPLOY_COMMAND);

expect(exitCode).toBe(0);
expect(readBuildDelegateArgv()).toEqual(["build"]);
expect(schedulesRequest).toEqual({
account: "production-account",
authorization: "Bearer production-token",
});
});
});

it("skips the build and deploys existing triggers with --prebuilt", async () => {
let schedulesBody: unknown;
let schedulesAccount: unknown;
Expand Down
52 changes: 52 additions & 0 deletions packages/cli/src/__tests__/commands/versions-upload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,58 @@ describe("cf workers versions create", () => {
expect(upload.metadata?.main_module).toBe("index.js");
});

it("loads dotenv files for the recorded mode when --prebuilt omits --mode", async () => {
vi.stubEnv("CLOUDFLARE_API_TOKEN", undefined);
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined);
let uploadRequest:
| { account: string | undefined; authorization: string | null }
| undefined;
mockWorkerUpload(
{},
{
onRequest: (request) => {
uploadRequest = {
account: new URL(request.url).pathname.match(
/\/accounts\/([^/]+)\//
)?.[1],
authorization: request.headers.get("authorization"),
};
},
}
);
await seed({
".env": [
"CLOUDFLARE_API_TOKEN=default-token",
"CLOUDFLARE_ACCOUNT_ID=default-account",
].join("\n"),
".env.staging": [
"CLOUDFLARE_API_TOKEN=staging-token",
"CLOUDFLARE_ACCOUNT_ID=staging-account",
].join("\n"),
".cloudflare/output/v1/config.json": buildOutputRootConfig({
buildContext: { isPreview: false, mode: "staging" },
}),
".cloudflare/output/v1/workers/default/worker.config.json":
workerConfig(),
".cloudflare/output/v1/workers/default/bundle/index.js":
"export default { fetch() { return new Response('ok'); } }",
});

const { exitCode } = await runCf([
"workers",
"versions",
"create",
"--prebuilt",
]);

expect(exitCode).toBe(0);
expect(uploadRequest).toEqual({
account: "staging-account",
authorization: "Bearer staging-token",
});
expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBeUndefined();
});

it("points Preview Build Output to a mode-aware Preview deploy", async () => {
const upload = mockWorkerUpload();
await seed({
Expand Down
18 changes: 10 additions & 8 deletions packages/cli/src/commands/deploy/shared.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { readBuildOutput } from "@cloudflare/build-output-utils";
import {
configureOpenAPIForContainerPull,
initContainersSharedContext,
Expand All @@ -13,6 +12,7 @@ import {
getCloudflareComplianceRegion,
} from "@cloudflare/workers-utils";
import { resolveBuildOutputAuth } from "../../lib/build-output-auth.js";
import { withBuildOutputDotEnv } from "../../lib/build-output-dotenv.js";
import {
applyCIMatchWorkerTag,
applyCIWorkerNameOverride,
Expand All @@ -30,12 +30,12 @@ import {
createDeployProps,
createVersionsUploadProps,
} from "../../lib/deploy-input.js";
import { withCloudflareDotEnv } from "../../lib/dotenv.js";
import { log } from "../../lib/ui/log.js";
import { runBuild } from "../build/index.js";
import { createContainerDeployConfig } from "./containers.js";
import { secretsFileDescription } from "./secrets-file-description.js";
import type { CommonYargsOptions, InferArgs } from "../../lib/cli-types.js";
import type { BuildOutput } from "@cloudflare/build-output-utils";
import type { Argv } from "yargs";

/**
Expand Down Expand Up @@ -108,14 +108,16 @@ export async function runUpload(argv: UploadArgs, ctx: UploadCommand) {
log.message("");
}

return withCloudflareDotEnv(argv, () => uploadBuildOutput(argv, ctx));
return withBuildOutputDotEnv((output) =>
uploadBuildOutput(argv, ctx, output)
);
}

async function uploadBuildOutput(argv: UploadArgs, ctx: UploadCommand) {
// Parse the build output with cf's dotenv values available.
const { root, workers, rootConfig, containers } = await readBuildOutput(
process.cwd()
);
async function uploadBuildOutput(
argv: UploadArgs,
ctx: UploadCommand,
{ root, workers, rootConfig, containers }: BuildOutput
) {
// --prebuilt can reuse files left behind by a Preview build.
// Stop here so a production deploy cannot publish that Preview configuration.
if (rootConfig.buildContext.isPreview) {
Expand Down
Loading
Loading