Skip to content

Commit 715ca2a

Browse files
add a util to format compatibility dates (#10043)
Co-authored-by: Pete Bacon Darwin <[email protected]>
1 parent e50d5f7 commit 715ca2a

File tree

11 files changed

+58
-42
lines changed

11 files changed

+58
-42
lines changed

packages/wrangler/e2e/pages-dev.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import getPort from "get-port";
55
import dedent from "ts-dedent";
66
import { fetch } from "undici";
77
import { describe, expect, it } from "vitest";
8+
import { formatCompatibilityDate } from "../src/utils/compatibility-date";
89
import { WranglerE2ETestHelper } from "./helpers/e2e-wrangler-test";
910
import { fetchText } from "./helpers/fetch-text";
1011
import { normalizeOutput } from "./helpers/normalize";
@@ -28,7 +29,7 @@ describe.sequential("wrangler pages dev", () => {
2829
);
2930
const { url } = await worker.waitForReady();
3031

31-
const currentDate = new Date().toISOString().substring(0, 10);
32+
const currentDate = formatCompatibilityDate(new Date());
3233
const output = worker.currentOutput.replaceAll(
3334
currentDate,
3435
"<current-date>"

packages/wrangler/src/__tests__/deploy.test.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5353,6 +5353,14 @@ addEventListener('fetch', event => {});`
53535353
});
53545354

53555355
describe("workers_dev setting", () => {
5356+
beforeEach(() => {
5357+
vi.useFakeTimers();
5358+
});
5359+
5360+
afterEach(() => {
5361+
vi.useRealTimers();
5362+
});
5363+
53565364
it("should deploy to a workers.dev domain if workers_dev is undefined", async () => {
53575365
writeWranglerConfig();
53585366
writeWorkerSource();
@@ -5788,26 +5796,20 @@ addEventListener('fetch', event => {});`
57885796
`);
57895797
});
57905798

5791-
it("should error if a compatibility_date is missing and suggest the correct month", async () => {
5792-
vi.spyOn(Date.prototype, "getMonth").mockImplementation(() => 11);
5793-
vi.spyOn(Date.prototype, "getFullYear").mockImplementation(() => 2020);
5794-
vi.spyOn(Date.prototype, "getDate").mockImplementation(() => 1);
5799+
it("should error if a compatibility_date is missing and suggest the correct date", async () => {
5800+
vi.setSystemTime(new Date(2020, 11, 1));
57955801

57965802
writeWorkerSource();
5797-
let err: undefined | Error;
5798-
try {
5799-
await runWrangler("deploy ./index.js --name my-worker");
5800-
} catch (e) {
5801-
err = e as Error;
5802-
}
58035803

5804-
expect(err?.message).toMatchInlineSnapshot(`
5805-
"A compatibility_date is required when publishing. Add the following to your Wrangler configuration file:
5804+
await expect(
5805+
async () => await runWrangler("deploy ./index.js --name my-worker")
5806+
).rejects.toThrowErrorMatchingInlineSnapshot(`
5807+
[Error: A compatibility_date is required when publishing. Add the following to your Wrangler configuration file:
58065808
\`\`\`
5807-
{\\"compatibility_date\\":\\"2020-12-01\\"}
5809+
{"compatibility_date":"2020-12-01"}
58085810
\`\`\`
58095811
Or you could pass it in your terminal as \`--compatibility-date 2020-12-01\`
5810-
See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
5812+
See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.]
58115813
`);
58125814
});
58135815

packages/wrangler/src/api/startDevWorker/ConfigController.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@ import {
2828
requireApiToken,
2929
requireAuth,
3030
} from "../../user";
31+
import { getDevCompatibilityDate } from "../../utils/compatibility-date";
3132
import {
3233
DEFAULT_INSPECTOR_PORT,
3334
DEFAULT_LOCAL_PORT,
3435
} from "../../utils/constants";
35-
import { getDevCompatibilityDate } from "../../utils/getDevCompatibilityDate";
3636
import { getRules } from "../../utils/getRules";
3737
import { getScriptName } from "../../utils/getScriptName";
3838
import { isLegacyEnv } from "../../utils/isLegacyEnv";

packages/wrangler/src/deploy/deploy.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import {
4949
maybeRetrieveFileSourceMap,
5050
} from "../sourcemap";
5151
import triggersDeploy from "../triggers/deploy";
52+
import { formatCompatibilityDate } from "../utils/compatibility-date";
5253
import { helpIfErrorIsSizeOrScriptStartup } from "../utils/friendly-validator-errors";
5354
import { printBindings } from "../utils/print-bindings";
5455
import { retryOnAPIFailure } from "../utils/retry";
@@ -399,11 +400,7 @@ export default async function deploy(props: Props): Promise<{
399400
}
400401

401402
if (!(props.compatibilityDate || config.compatibility_date)) {
402-
const compatibilityDateStr = `${new Date().getFullYear()}-${(
403-
new Date().getMonth() +
404-
1 +
405-
""
406-
).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
403+
const compatibilityDateStr = formatCompatibilityDate(new Date());
407404

408405
throw new UserError(
409406
`A compatibility_date is required when publishing. Add the following to your ${configFileName(config.configPath)} file:

packages/wrangler/src/deploy/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { writeOutput } from "../output";
1313
import { getSiteAssetPaths } from "../sites";
1414
import { requireAuth } from "../user";
1515
import { collectKeyValues } from "../utils/collectKeyValues";
16+
import { formatCompatibilityDate } from "../utils/compatibility-date";
1617
import { getRules } from "../utils/getRules";
1718
import { getScriptName } from "../utils/getScriptName";
1819
import { isLegacyEnv } from "../utils/isLegacyEnv";
@@ -307,7 +308,7 @@ export const deployCommand = createCommand({
307308
entry,
308309
env: args.env,
309310
compatibilityDate: args.latest
310-
? new Date().toISOString().substring(0, 10)
311+
? formatCompatibilityDate(new Date())
311312
: args.compatibilityDate,
312313
compatibilityFlags: args.compatibilityFlags,
313314
vars: cliVars,

packages/wrangler/src/deployment-bundle/entry.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import dedent from "ts-dedent";
33
import { configFileName, formatConfigSnippet } from "../config";
44
import { UserError } from "../errors";
55
import { sniffUserAgent } from "../package-manager";
6+
import { formatCompatibilityDate } from "../utils/compatibility-date";
67
import guessWorkerFormat from "./guess-worker-format";
78
import {
89
resolveEntryWithAssets,
@@ -75,11 +76,7 @@ export async function getEntry(
7576
);
7677
}
7778

78-
const compatibilityDateStr = [
79-
new Date().getFullYear(),
80-
(new Date().getMonth() + 1 + "").padStart(2, "0"),
81-
(new Date().getDate() + "").padStart(2, "0"),
82-
].join("-");
79+
const compatibilityDateStr = formatCompatibilityDate(new Date());
8380

8481
const updateConfigMessage = (snippet: RawConfig) => dedent`
8582
${

packages/wrangler/src/init.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { logger } from "./logger";
1616
import { readMetricsConfig } from "./metrics/metrics-config";
1717
import { getPackageManager } from "./package-manager";
1818
import { requireAuth } from "./user";
19+
import { formatCompatibilityDate } from "./utils/compatibility-date";
1920
import { createBatches } from "./utils/create-batches";
2021
import * as shellquote from "./utils/shell-quote";
2122
import type { RawConfig } from "./config";
@@ -305,7 +306,7 @@ async function getWorkerConfig(
305306
workers_dev: workersDev.enabled,
306307
compatibility_date:
307308
serviceEnvMetadata.script.compatibility_date ??
308-
new Date().toISOString().substring(0, 10),
309+
formatCompatibilityDate(new Date()),
309310
compatibility_flags: serviceEnvMetadata.script.compatibility_flags,
310311
...(allRoutes.length ? { routes: allRoutes } : {}),
311312
placement:

packages/wrangler/src/pages/dev.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { logger } from "../logger";
1717
import * as metrics from "../metrics";
1818
import { isNavigatorDefined } from "../navigator-user-agent";
1919
import { getBasePath } from "../paths";
20+
import { formatCompatibilityDate } from "../utils/compatibility-date";
2021
import { debounce } from "../utils/debounce";
2122
import * as shellquote from "../utils/shell-quote";
2223
import { buildFunctions } from "./buildFunctions";
@@ -1140,7 +1141,7 @@ function resolvePagesDevServerSettings(
11401141
// resolve compatibility date
11411142
let compatibilityDate = args.compatibilityDate || config.compatibility_date;
11421143
if (!compatibilityDate) {
1143-
const currentDate = new Date().toISOString().substring(0, 10);
1144+
const currentDate = formatCompatibilityDate(new Date());
11441145
logger.warn(
11451146
`No compatibility_date was specified. Using today's date: ${currentDate}.\n` +
11461147
`❯❯ Add one to your ${configFileName(config.configPath)} file: compatibility_date = "${currentDate}", or\n` +

packages/wrangler/src/pages/download-config.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { FatalError } from "../errors";
1212
import { logger } from "../logger";
1313
import * as metrics from "../metrics";
1414
import { requireAuth } from "../user";
15+
import { formatCompatibilityDate } from "../utils/compatibility-date";
1516
import { PAGES_CONFIG_CACHE_FILENAME } from "./constants";
1617
import type { RawEnvironment } from "../config";
1718
import type { PagesConfigCache } from "./types";
@@ -71,8 +72,7 @@ async function toEnvironment(
7172
): Promise<RawEnvironment> {
7273
const configObj = {} as RawEnvironment;
7374
configObj.compatibility_date =
74-
deploymentConfig.compatibility_date ??
75-
new Date().toISOString().substring(0, 10);
75+
deploymentConfig.compatibility_date ?? formatCompatibilityDate(new Date());
7676

7777
// Find the latest supported compatibility date and use that
7878
if (deploymentConfig.always_use_latest_compatibility_date) {

packages/wrangler/src/utils/getDevCompatibilityDate.ts renamed to packages/wrangler/src/utils/compatibility-date.ts

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@ import { configFileName } from "../config";
33
import { logger } from "../logger";
44
import type { Config } from "../config";
55

6+
/**
7+
* Returns the compatibility date to use in development.
8+
*
9+
* When no compatibility date is configured, uses the installed Workers runtime's latest supported date.
10+
*
11+
* @param config wrangler configuration
12+
* @param compatibilityDate configured compatibility date
13+
* @returns the compatibility date to use in development
14+
*/
615
export function getDevCompatibilityDate(
716
config: Config,
817
compatibilityDate = config.compatibility_date
@@ -13,15 +22,25 @@ export function getDevCompatibilityDate(
1322
const miniflareWorkerd = miniflareRequire("workerd") as {
1423
compatibilityDate: string;
1524
};
16-
const currentDate = miniflareWorkerd.compatibilityDate;
25+
const workerdDate = miniflareWorkerd.compatibilityDate;
1726

1827
if (config.configPath !== undefined && compatibilityDate === undefined) {
1928
logger.warn(
20-
`No compatibility_date was specified. Using the installed Workers runtime's latest supported date: ${currentDate}.\n` +
21-
`❯❯ Add one to your ${configFileName(config.configPath)} file: compatibility_date = "${currentDate}", or\n` +
22-
`❯❯ Pass it in your terminal: wrangler dev [<SCRIPT>] --compatibility-date=${currentDate}\n\n` +
29+
`No compatibility_date was specified. Using the installed Workers runtime's latest supported date: ${workerdDate}.\n` +
30+
`❯❯ Add one to your ${configFileName(config.configPath)} file: compatibility_date = "${workerdDate}", or\n` +
31+
`❯❯ Pass it in your terminal: wrangler dev [<SCRIPT>] --compatibility-date=${workerdDate}\n\n` +
2332
"See https://developers.cloudflare.com/workers/platform/compatibility-dates/ for more information."
2433
);
2534
}
26-
return compatibilityDate ?? currentDate;
35+
return compatibilityDate ?? workerdDate;
36+
}
37+
38+
/**
39+
* Returns the date formatted as a compatibility date
40+
*
41+
* @param date
42+
* @returns The date as a `YYYY-MM-DD` string
43+
*/
44+
export function formatCompatibilityDate(date: Date): string {
45+
return date.toISOString().slice(0, 10);
2746
}

0 commit comments

Comments
 (0)