wrangler 0.0.0-e3cab74 → 0.0.0-e3e3243

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 (66) hide show
  1. package/README.md +1 -1
  2. package/bin/wrangler.js +10 -1
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +10 -7
  6. package/pages/functions/filepath-routing.test.ts +125 -25
  7. package/pages/functions/filepath-routing.ts +6 -3
  8. package/src/__tests__/configuration.test.ts +959 -324
  9. package/src/__tests__/dev.test.tsx +512 -84
  10. package/src/__tests__/guess-worker-format.test.ts +19 -17
  11. package/src/__tests__/helpers/mock-account-id.ts +22 -4
  12. package/src/__tests__/helpers/mock-cfetch.ts +3 -3
  13. package/src/__tests__/helpers/mock-console.ts +17 -9
  14. package/src/__tests__/helpers/mock-kv.ts +9 -16
  15. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  16. package/src/__tests__/helpers/run-in-tmp.ts +3 -0
  17. package/src/__tests__/https-options.test.ts +127 -0
  18. package/src/__tests__/index.test.ts +128 -11
  19. package/src/__tests__/jest.setup.ts +16 -4
  20. package/src/__tests__/kv.test.ts +364 -125
  21. package/src/__tests__/logout.test.ts +15 -13
  22. package/src/__tests__/pages.test.ts +82 -0
  23. package/src/__tests__/publish.test.ts +1838 -735
  24. package/src/__tests__/r2.test.ts +4 -4
  25. package/src/__tests__/route.test.ts +45 -0
  26. package/src/__tests__/secret.test.ts +167 -68
  27. package/src/__tests__/tail.test.ts +2 -4
  28. package/src/__tests__/whoami.test.tsx +21 -7
  29. package/src/bundle.ts +27 -5
  30. package/src/cfetch/internal.ts +11 -5
  31. package/src/config/README.md +6 -6
  32. package/src/config/config.ts +54 -101
  33. package/src/config/environment.ts +67 -1
  34. package/src/config/index.ts +13 -3
  35. package/src/config/validation-helpers.ts +207 -23
  36. package/src/config/validation.ts +344 -129
  37. package/src/{api/preview.ts → create-worker-preview.ts} +39 -20
  38. package/src/{api/form_data.ts → create-worker-upload-form.ts} +1 -1
  39. package/src/dev/dev.tsx +392 -0
  40. package/src/dev/local.tsx +232 -0
  41. package/src/dev/remote.tsx +203 -0
  42. package/src/dev/use-esbuild.ts +104 -0
  43. package/src/entry.ts +192 -9
  44. package/src/https-options.ts +122 -0
  45. package/src/index.tsx +577 -515
  46. package/src/inspect.ts +9 -1
  47. package/src/intl-polyfill.d.ts +139 -0
  48. package/src/{kv.tsx → kv.ts} +97 -53
  49. package/src/miniflare-cli/README.md +30 -0
  50. package/src/miniflare-cli/enum-keys.ts +17 -0
  51. package/src/miniflare-cli/index.ts +37 -0
  52. package/src/module-collection.ts +90 -2
  53. package/src/open-in-browser.ts +14 -2
  54. package/src/pages.tsx +26 -10
  55. package/src/proxy.ts +104 -40
  56. package/src/publish.ts +53 -71
  57. package/src/reporting.ts +25 -9
  58. package/src/selfsigned.d.ts +29 -0
  59. package/src/sites.tsx +68 -29
  60. package/src/user.tsx +163 -85
  61. package/src/{api/worker.ts → worker.ts} +1 -24
  62. package/wrangler-dist/cli.js +5933 -3842
  63. package/wrangler-dist/cli.js.map +3 -3
  64. package/src/__tests__/helpers/mock-user.ts +0 -27
  65. package/src/dev.tsx +0 -961
  66. package/src/guess-worker-format.ts +0 -68
@@ -90,7 +90,7 @@ describe("wrangler", () => {
90
90
  await expect(
91
91
  runWrangler("r2 bucket create abc def ghi")
92
92
  ).rejects.toThrowErrorMatchingInlineSnapshot(
93
- `"Unexpected additional positional arguments \\"def ghi\\"."`
93
+ `"Unknown arguments: def, ghi"`
94
94
  );
95
95
  expect(std.out).toMatchInlineSnapshot(`""`);
96
96
  expect(std.err).toMatchInlineSnapshot(`
@@ -107,7 +107,7 @@ describe("wrangler", () => {
107
107
  -v, --version Show version number [boolean]
108
108
  --legacy-env Use legacy environments [boolean]
109
109
 
110
- Unexpected additional positional arguments \\"def ghi\\"."
110
+ Unknown arguments: def, ghi"
111
111
  `);
112
112
  });
113
113
 
@@ -166,7 +166,7 @@ describe("wrangler", () => {
166
166
  await expect(
167
167
  runWrangler("r2 bucket delete abc def ghi")
168
168
  ).rejects.toThrowErrorMatchingInlineSnapshot(
169
- `"Unexpected additional positional arguments \\"def ghi\\"."`
169
+ `"Unknown arguments: def, ghi"`
170
170
  );
171
171
  expect(std.out).toMatchInlineSnapshot(`""`);
172
172
  expect(std.err).toMatchInlineSnapshot(`
@@ -183,7 +183,7 @@ describe("wrangler", () => {
183
183
  -v, --version Show version number [boolean]
184
184
  --legacy-env Use legacy environments [boolean]
185
185
 
186
- Unexpected additional positional arguments \\"def ghi\\"."
186
+ Unknown arguments: def, ghi"
187
187
  `);
188
188
  });
189
189
 
@@ -0,0 +1,45 @@
1
+ import { mockConsoleMethods } from "./helpers/mock-console";
2
+ import { runInTempDir } from "./helpers/run-in-tmp";
3
+ import { runWrangler } from "./helpers/run-wrangler";
4
+
5
+ describe("wrangler route", () => {
6
+ mockConsoleMethods();
7
+ runInTempDir();
8
+
9
+ it("shows a deprecation notice when `wrangler route` is run", async () => {
10
+ await expect(runWrangler("route")).rejects
11
+ .toThrowErrorMatchingInlineSnapshot(`
12
+ "DEPRECATION WARNING:
13
+ \`wrangler route\` has been deprecated.
14
+ Please use wrangler.toml and/or \`wrangler publish --routes\` to modify routes"
15
+ `);
16
+ });
17
+
18
+ it("shows a deprecation notice when `wrangler route delete` is run", async () => {
19
+ await expect(runWrangler("route delete")).rejects
20
+ .toThrowErrorMatchingInlineSnapshot(`
21
+ "DEPRECATION WARNING:
22
+ \`wrangler route delete\` has been deprecated.
23
+ Remove the unwanted route(s) from wrangler.toml and run \`wrangler publish\` to remove your worker from those routes."
24
+ `);
25
+ });
26
+
27
+ it("shows a deprecation notice when `wrangler route delete <id>` is run", async () => {
28
+ await expect(runWrangler("route delete some-zone-id")).rejects
29
+ .toThrowErrorMatchingInlineSnapshot(`
30
+ "DEPRECATION WARNING:
31
+ \`wrangler route delete\` has been deprecated.
32
+ Remove the unwanted route(s) from wrangler.toml and run \`wrangler publish\` to remove your worker from those routes."
33
+ `);
34
+ });
35
+
36
+ it("shows a deprecation notice when `wrangler route list` is run", async () => {
37
+ await expect(runWrangler("route list")).rejects
38
+ .toThrowErrorMatchingInlineSnapshot(`
39
+ "DEPRECATION WARNING:
40
+ \`wrangler route list\` has been deprecated.
41
+ Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.
42
+ Refer to the Cloudflare Dashboard to see the routes this worker is currently running on."
43
+ `);
44
+ });
45
+ });
@@ -1,7 +1,11 @@
1
+ import * as fs from "node:fs";
2
+ import * as TOML from "@iarna/toml";
3
+ import fetchMock from "jest-fetch-mock";
1
4
  import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
2
5
  import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
3
6
  import { mockConsoleMethods } from "./helpers/mock-console";
4
7
  import { mockConfirm, mockPrompt } from "./helpers/mock-dialogs";
8
+ import { useMockStdin } from "./helpers/mock-stdin";
5
9
  import { runInTempDir } from "./helpers/run-in-tmp";
6
10
  import { runWrangler } from "./helpers/run-wrangler";
7
11
 
@@ -44,84 +48,181 @@ describe("wrangler secret", () => {
44
48
  );
45
49
  }
46
50
 
47
- it("should create a secret", async () => {
48
- mockPrompt({
49
- text: "Enter a secret value:",
50
- type: "password",
51
- result: "the-secret",
51
+ describe("interactive", () => {
52
+ useMockStdin({ isTTY: true });
53
+
54
+ it("should create a secret", async () => {
55
+ mockPrompt({
56
+ text: "Enter a secret value:",
57
+ type: "password",
58
+ result: "the-secret",
59
+ });
60
+
61
+ mockPutRequest({ name: "the-key", text: "the-secret" });
62
+ await runWrangler("secret put the-key --name script-name");
63
+
64
+ expect(std.out).toMatchInlineSnapshot(`
65
+ "🌀 Creating the secret for script script-name
66
+ ✨ Success! Uploaded secret the-key"
67
+ `);
68
+ expect(std.err).toMatchInlineSnapshot(`""`);
52
69
  });
53
70
 
54
- mockPutRequest({ name: "the-secret-name", text: "the-secret" });
55
- await runWrangler("secret put the-key --name script-name");
71
+ it("should create a secret: legacy envs", async () => {
72
+ mockPrompt({
73
+ text: "Enter a secret value:",
74
+ type: "password",
75
+ result: "the-secret",
76
+ });
56
77
 
57
- expect(std.out).toMatchInlineSnapshot(`
58
- "🌀 Creating the secret for script script-name
59
- ✨ Success! Uploaded secret the-key"
60
- `);
61
- expect(std.err).toMatchInlineSnapshot(`""`);
62
- });
78
+ mockPutRequest(
79
+ { name: "the-key", text: "the-secret" },
80
+ "some-env",
81
+ true
82
+ );
83
+ await runWrangler(
84
+ "secret put the-key --name script-name --env some-env --legacy-env"
85
+ );
63
86
 
64
- it("should create a secret: legacy envs", async () => {
65
- mockPrompt({
66
- text: "Enter a secret value:",
67
- type: "password",
68
- result: "the-secret",
87
+ expect(std.out).toMatchInlineSnapshot(`
88
+ "🌀 Creating the secret for script script-name-some-env
89
+ ✨ Success! Uploaded secret the-key"
90
+ `);
91
+ expect(std.err).toMatchInlineSnapshot(`""`);
69
92
  });
70
93
 
71
- mockPutRequest(
72
- { name: "the-secret-name", text: "the-secret" },
73
- "some-env",
74
- true
75
- );
76
- await runWrangler(
77
- "secret put the-key --name script-name --env some-env --legacy-env"
78
- );
94
+ it("should create a secret: service envs", async () => {
95
+ mockPrompt({
96
+ text: "Enter a secret value:",
97
+ type: "password",
98
+ result: "the-secret",
99
+ });
79
100
 
80
- expect(std.out).toMatchInlineSnapshot(`
81
- "🌀 Creating the secret for script script-name-some-env
82
- ✨ Success! Uploaded secret the-key"
83
- `);
84
- expect(std.err).toMatchInlineSnapshot(`""`);
85
- });
101
+ mockPutRequest(
102
+ { name: "the-key", text: "the-secret" },
103
+ "some-env",
104
+ false
105
+ );
106
+ await runWrangler(
107
+ "secret put the-key --name script-name --env some-env --legacy-env false"
108
+ );
86
109
 
87
- it("should create a secret: service envs", async () => {
88
- mockPrompt({
89
- text: "Enter a secret value:",
90
- type: "password",
91
- result: "the-secret",
110
+ expect(std.out).toMatchInlineSnapshot(`
111
+ "🌀 Creating the secret for script script-name (some-env)
112
+ ✨ Success! Uploaded secret the-key"
113
+ `);
114
+ expect(std.err).toMatchInlineSnapshot(`""`);
92
115
  });
93
116
 
94
- mockPutRequest(
95
- { name: "the-secret-name", text: "the-secret" },
96
- "some-env",
97
- false
98
- );
99
- await runWrangler(
100
- "secret put the-key --name script-name --env some-env --legacy-env false"
101
- );
117
+ it("should error without a script name", async () => {
118
+ let error: Error | undefined;
119
+ try {
120
+ await runWrangler("secret put the-key");
121
+ } catch (e) {
122
+ error = e as Error;
123
+ }
124
+ expect(std.out).toMatchInlineSnapshot(`""`);
125
+ expect(std.err).toMatchInlineSnapshot(`
126
+ "Missing script name
102
127
 
103
- expect(std.out).toMatchInlineSnapshot(`
104
- "🌀 Creating the secret for script script-name (some-env)
105
- ✨ Success! Uploaded secret the-key"
106
- `);
107
- expect(std.err).toMatchInlineSnapshot(`""`);
128
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
129
+ `);
130
+ expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
131
+ });
108
132
  });
109
133
 
110
- it("should error without a script name", async () => {
111
- let error: Error | undefined;
112
- try {
113
- await runWrangler("secret put the-key");
114
- } catch (e) {
115
- error = e as Error;
116
- }
117
- expect(std.out).toMatchInlineSnapshot(`""`);
118
- expect(std.err).toMatchInlineSnapshot(`
119
- "Missing script name
134
+ describe("non-interactive", () => {
135
+ const mockStdIn = useMockStdin({ isTTY: false });
120
136
 
121
- %s
122
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
123
- `);
124
- expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
137
+ it("should create a secret, from piped input", async () => {
138
+ mockPutRequest({ name: "the-key", text: "the-secret" });
139
+ // Pipe the secret in as three chunks to test that we reconstitute it correctly.
140
+ mockStdIn.send("the", "-", "secret");
141
+ await runWrangler("secret put the-key --name script-name");
142
+
143
+ expect(std.out).toMatchInlineSnapshot(`
144
+ "🌀 Creating the secret for script script-name
145
+ ✨ Success! Uploaded secret the-key"
146
+ `);
147
+ expect(std.warn).toMatchInlineSnapshot(`""`);
148
+ expect(std.err).toMatchInlineSnapshot(`""`);
149
+ });
150
+
151
+ it("should error if the piped input fails", async () => {
152
+ mockPutRequest({ name: "the-key", text: "the-secret" });
153
+ mockStdIn.throwError(new Error("Error in stdin stream"));
154
+ await expect(
155
+ runWrangler("secret put the-key --name script-name")
156
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`"Error in stdin stream"`);
157
+
158
+ expect(std.out).toMatchInlineSnapshot(`""`);
159
+ expect(std.warn).toMatchInlineSnapshot(`""`);
160
+ });
161
+
162
+ describe("with accountId", () => {
163
+ mockAccountId({ accountId: null });
164
+
165
+ it("should error if a user has no account", async () => {
166
+ await expect(
167
+ runWrangler("secret put the-key --name script-name")
168
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
169
+ `"No account id found, quitting..."`
170
+ );
171
+ });
172
+
173
+ it("should use the account from wrangler.toml", async () => {
174
+ fs.writeFileSync(
175
+ "wrangler.toml",
176
+ TOML.stringify({
177
+ account_id: "some-account-id",
178
+ }),
179
+ "utf-8"
180
+ );
181
+ mockStdIn.send("the-secret");
182
+ mockPutRequest({ name: "the-key", text: "the-secret" });
183
+ await runWrangler("secret put the-key --name script-name");
184
+ expect(std.out).toMatchInlineSnapshot(`
185
+ "🌀 Creating the secret for script script-name
186
+ ✨ Success! Uploaded secret the-key"
187
+ `);
188
+ expect(std.warn).toMatchInlineSnapshot(`""`);
189
+ expect(std.err).toMatchInlineSnapshot(`""`);
190
+ });
191
+
192
+ it("should error if a user has multiple accounts, and has not specified an account in wrangler.toml", async () => {
193
+ // This is a mock response for the request to the CF API memberships of the current user.
194
+ fetchMock.doMockOnce(async () => {
195
+ return {
196
+ body: JSON.stringify({
197
+ success: true,
198
+ result: [
199
+ {
200
+ id: "1",
201
+ account: { id: "account-id-1", name: "account-name-1" },
202
+ },
203
+ {
204
+ id: "2",
205
+ account: { id: "account-id-2", name: "account-name-2" },
206
+ },
207
+ {
208
+ id: "3",
209
+ account: { id: "account-id-3", name: "account-name-3" },
210
+ },
211
+ ],
212
+ }),
213
+ };
214
+ });
215
+ await expect(runWrangler("secret put the-key --name script-name"))
216
+ .rejects.toThrowErrorMatchingInlineSnapshot(`
217
+ "More than one account available but unable to select one in non-interactive mode.
218
+ Please set the appropriate \`account_id\` in your \`wrangler.toml\` file.
219
+ Available accounts are (\\"<name>\\" - \\"<id>\\"):
220
+ \\"account-name-1\\" - \\"account-id-1\\")
221
+ \\"account-name-2\\" - \\"account-id-2\\")
222
+ \\"account-name-3\\" - \\"account-id-3\\")"
223
+ `);
224
+ });
225
+ });
125
226
  });
126
227
  });
127
228
 
@@ -223,8 +324,7 @@ describe("wrangler secret", () => {
223
324
  expect(std.err).toMatchInlineSnapshot(`
224
325
  "Missing script name
225
326
 
226
- %s
227
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
327
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
228
328
  `);
229
329
  expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
230
330
  });
@@ -317,8 +417,7 @@ describe("wrangler secret", () => {
317
417
  expect(std.err).toMatchInlineSnapshot(`
318
418
  "Missing script name
319
419
 
320
- %s
321
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
420
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
322
421
  `);
323
422
  expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
324
423
  });
@@ -134,7 +134,7 @@ describe("tail", () => {
134
134
 
135
135
  it("sends header filters without a query", async () => {
136
136
  const api = mockWebsocketAPIs();
137
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER ");
137
+ await runWrangler("tail test-worker --header X-CUSTOM-HEADER");
138
138
  await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
139
139
  { header: { key: "X-CUSTOM-HEADER" } },
140
140
  ]);
@@ -142,9 +142,7 @@ describe("tail", () => {
142
142
 
143
143
  it("sends header filters with a query", async () => {
144
144
  const api = mockWebsocketAPIs();
145
- await runWrangler(
146
- "tail test-worker --header X-CUSTOM-HEADER:some-value "
147
- );
145
+ await runWrangler("tail test-worker --header X-CUSTOM-HEADER:some-value");
148
146
  await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
149
147
  { header: { key: "X-CUSTOM-HEADER", query: "some-value" } },
150
148
  ]);
@@ -1,30 +1,34 @@
1
1
  import { render } from "ink-testing-library";
2
2
  import React from "react";
3
- import { initialise } from "../user";
3
+ import { reinitialiseAuthTokens, writeAuthConfigFile } from "../user";
4
4
  import { getUserInfo, WhoAmI } from "../whoami";
5
5
  import { setMockResponse } from "./helpers/mock-cfetch";
6
- import { writeUserConfig } from "./helpers/mock-user";
6
+ import { mockConsoleMethods } from "./helpers/mock-console";
7
7
  import { runInTempDir } from "./helpers/run-in-tmp";
8
8
  import type { UserInfo } from "../whoami";
9
9
 
10
10
  describe("getUserInfo()", () => {
11
11
  runInTempDir({ homedir: "./home" });
12
+ const std = mockConsoleMethods();
12
13
 
13
14
  it("should return undefined if there is no config file", async () => {
14
- await initialise();
15
15
  const userInfo = await getUserInfo();
16
16
  expect(userInfo).toBeUndefined();
17
17
  });
18
18
 
19
19
  it("should return undefined if there is an empty config file", async () => {
20
- writeUserConfig();
21
- await initialise();
20
+ writeAuthConfigFile({});
21
+ // Now that we have changed the auth tokens in the wrangler.toml we must reinitialize the user auth state.
22
+ reinitialiseAuthTokens();
22
23
  const userInfo = await getUserInfo();
23
24
  expect(userInfo).toBeUndefined();
24
25
  });
25
26
 
26
27
  it("should return the user's email and accounts if authenticated via config token", async () => {
27
- writeUserConfig("some-oauth-token");
28
+ writeAuthConfigFile({ oauth_token: "some-oauth-token" });
29
+ // Now that we have changed the auth tokens in the wrangler.toml we must reinitialize the user auth state.
30
+ reinitialiseAuthTokens();
31
+
28
32
  setMockResponse("/user", () => {
29
33
  return { email: "user@example.com" };
30
34
  });
@@ -36,7 +40,6 @@ describe("getUserInfo()", () => {
36
40
  ];
37
41
  });
38
42
 
39
- await initialise();
40
43
  const userInfo = await getUserInfo();
41
44
 
42
45
  expect(userInfo).toEqual({
@@ -50,6 +53,17 @@ describe("getUserInfo()", () => {
50
53
  ],
51
54
  });
52
55
  });
56
+
57
+ it("should display a warning message if the config file contains a legacy api_token field", async () => {
58
+ writeAuthConfigFile({ api_token: "API_TOKEN" });
59
+ await reinitialiseAuthTokens();
60
+ await getUserInfo();
61
+ expect(std.warn).toMatchInlineSnapshot(`
62
+ "It looks like you have used Wrangler 1's \`config\` command to login with an API token.
63
+ This is no longer supported in the current version of Wrangler.
64
+ If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\` environment variable."
65
+ `);
66
+ });
53
67
  });
54
68
 
55
69
  describe("WhoAmI component", () => {
package/src/bundle.ts CHANGED
@@ -2,10 +2,10 @@ import assert from "node:assert";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import * as esbuild from "esbuild";
5
- import makeModuleCollector from "./module-collection";
6
- import type { CfModule, CfScriptFormat } from "./api/worker";
5
+ import createModuleCollector from "./module-collection";
7
6
  import type { Config } from "./config";
8
7
  import type { Entry } from "./entry";
8
+ import type { CfModule } from "./worker";
9
9
 
10
10
  type BundleResult = {
11
11
  modules: CfModule[];
@@ -24,20 +24,36 @@ export async function bundleWorker(
24
24
  serveAssetsFromWorker: boolean;
25
25
  jsxFactory: string | undefined;
26
26
  jsxFragment: string | undefined;
27
- format: CfScriptFormat;
28
27
  rules: Config["rules"];
29
28
  watch?: esbuild.WatchMode;
29
+ tsconfig: string | undefined;
30
30
  }
31
31
  ): Promise<BundleResult> {
32
32
  const {
33
33
  serveAssetsFromWorker,
34
34
  jsxFactory,
35
35
  jsxFragment,
36
- format,
37
36
  rules,
38
37
  watch,
38
+ tsconfig,
39
39
  } = options;
40
- const moduleCollector = makeModuleCollector({ format, rules });
40
+ const entryDirectory = path.dirname(entry.file);
41
+ const moduleCollector = createModuleCollector({
42
+ wrangler1xlegacyModuleReferences: {
43
+ rootDirectory: entryDirectory,
44
+ fileNames: new Set(
45
+ fs
46
+ .readdirSync(entryDirectory, { withFileTypes: true })
47
+ .filter(
48
+ (dirEntry) =>
49
+ dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
50
+ )
51
+ .map((dirEnt) => dirEnt.name)
52
+ ),
53
+ },
54
+ format: entry.format,
55
+ rules,
56
+ });
41
57
  const result = await esbuild.build({
42
58
  ...getEntryPoint(entry.file, serveAssetsFromWorker),
43
59
  bundle: true,
@@ -48,6 +64,11 @@ export async function bundleWorker(
48
64
  sourcemap: true,
49
65
  metafile: true,
50
66
  conditions: ["worker", "browser"],
67
+ ...(process.env.NODE_ENV && {
68
+ define: {
69
+ "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
70
+ },
71
+ }),
51
72
  loader: {
52
73
  ".js": "jsx",
53
74
  ".mjs": "jsx",
@@ -56,6 +77,7 @@ export async function bundleWorker(
56
77
  plugins: [moduleCollector.plugin],
57
78
  ...(jsxFactory && { jsxFactory }),
58
79
  ...(jsxFragment && { jsxFragment }),
80
+ ...(tsconfig && { tsconfig }),
59
81
  watch,
60
82
  });
61
83
 
@@ -1,6 +1,7 @@
1
- import { fetch } from "undici";
1
+ import { fetch, Headers } from "undici";
2
2
  import { getEnvironmentVariableFactory } from "../environment-variables";
3
3
  import { ParseError, parseJSON } from "../parse";
4
+ import { reportError } from "../reporting";
4
5
  import { getAPIToken, loginOrRefreshIfRequired } from "../user";
5
6
  import type { URLSearchParams } from "node:url";
6
7
  import type { RequestInit, HeadersInit } from "undici";
@@ -47,6 +48,7 @@ export async function fetchInternal<ResponseType>(
47
48
  try {
48
49
  return parseJSON(jsonText) as ResponseType;
49
50
  } catch (err) {
51
+ await reportError(err as Error);
50
52
  throw new ParseError({
51
53
  text: "Received a malformed response from the API",
52
54
  notes: [
@@ -72,7 +74,11 @@ function truncate(text: string, maxLength: number): string {
72
74
  function cloneHeaders(
73
75
  headers: HeadersInit | undefined
74
76
  ): Record<string, string> {
75
- return { ...headers };
77
+ return headers instanceof Headers
78
+ ? Object.fromEntries(headers.entries())
79
+ : Array.isArray(headers)
80
+ ? Object.fromEntries(headers)
81
+ : { ...headers };
76
82
  }
77
83
 
78
84
  async function requireLoggedIn(): Promise<void> {
@@ -83,11 +89,11 @@ async function requireLoggedIn(): Promise<void> {
83
89
  }
84
90
 
85
91
  function requireApiToken(): string {
86
- const apiToken = getAPIToken();
87
- if (!apiToken) {
92
+ const authToken = getAPIToken();
93
+ if (!authToken) {
88
94
  throw new Error("No API token found.");
89
95
  }
90
- return apiToken;
96
+ return authToken;
91
97
  }
92
98
 
93
99
  function addAuthorizationHeader(
@@ -25,24 +25,23 @@ This includes the `EnvironmentInheritable` and `EnvironmentNonInheritable` field
25
25
  ### Config
26
26
 
27
27
  The "non-overridable" types are defined in the [`ConfigFields`](./config.ts) type.
28
- Notably this also contains a property called `env` which is the container for the named environment configuration.
29
-
30
28
  The `Config` type is the overall configuration, which consists of the `ConfigFields` and also an `Environment`.
31
- In this case the `Environment`, here, corresponds to the top level environment.
29
+ In this case the `Environment`, here, corresponds to the "currently active" environment. This is specified by the `--env` command line argument.
30
+ If there is no argument passed then the currently active environment is the "top-level" environment.
32
31
  The fields in `Config` and `Environment` are not generally optional and so you can expect they have been filled with suitable inherited or default values.
33
32
  These types should be used when you are working with fields that should be passed to commands.
34
33
 
35
34
  ### RawConfig
36
35
 
37
36
  The `RawConfig` type is a version of `Config`, where all the fields are optional.
38
- The `RawConfig` type also includes `DeprecatedConfigFields` and extends and contains the `RawEnvironment` type,
39
- which is a version of `Environment` where all the fields are optional.
37
+ The `RawConfig` type includes `DeprecatedConfigFields` and `EnvironmentMap`.
38
+ It also extends the `RawEnvironment` type, which is a version of `Environment` where all the fields are optional.
40
39
  These optional fields map to the actual fields found in the `wrangler.toml`.
41
40
  These types should be used when you are working with raw configuration that is read or will be written to a `wrangler.toml`.
42
41
 
43
42
  ## Validation
44
43
 
45
- Validation is triggered by passing a `RawConfig` object to the `normalizeAndValidateConfig()` function.
44
+ Validation is triggered by passing a `RawConfig` object, and the active environment name, to the `normalizeAndValidateConfig()` function.
46
45
  This function will return:
47
46
 
48
47
  - a `Config` object, where all the fields have suitable valid values
@@ -62,6 +61,7 @@ The [high level API](./index.ts) for configuration processing consists of the `f
62
61
  ### readConfig()
63
62
 
64
63
  The `readConfig()` function will find the nearest `wrangler.toml` file, load and parse it, then validate and normalize the values into a `Config` object.
64
+ Note that you should pass the current active environment name in as a parameter. The resulting `Config` object will contain only the fields appropriate to that environment.
65
65
  If there are validation errors then it will throw a suitable error.
66
66
 
67
67
  ## Changing configuration