wrangler 0.0.0-e14e589 → 0.0.0-e151223

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 (55) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +2 -2
  3. package/package.json +46 -29
  4. package/pages/functions/buildWorker.ts +62 -0
  5. package/pages/functions/filepath-routing.test.ts +47 -0
  6. package/pages/functions/filepath-routing.ts +231 -0
  7. package/pages/functions/identifiers.ts +78 -0
  8. package/pages/functions/routes.ts +160 -0
  9. package/pages/functions/template-worker.ts +136 -0
  10. package/src/__tests__/dev.test.tsx +71 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  13. package/src/__tests__/helpers/mock-cfetch.ts +173 -0
  14. package/src/__tests__/helpers/mock-console.ts +56 -0
  15. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  16. package/src/__tests__/helpers/mock-kv.ts +40 -0
  17. package/src/__tests__/helpers/mock-user.ts +27 -0
  18. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  19. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  20. package/src/__tests__/index.test.ts +372 -119
  21. package/src/__tests__/jest.setup.ts +34 -0
  22. package/src/__tests__/kv.test.ts +1149 -0
  23. package/src/__tests__/logout.test.ts +50 -0
  24. package/src/__tests__/publish.test.ts +1222 -0
  25. package/src/__tests__/secret.test.ts +210 -0
  26. package/src/__tests__/whoami.test.tsx +86 -0
  27. package/src/api/form_data.ts +85 -76
  28. package/src/api/preview.ts +29 -24
  29. package/src/api/worker.ts +50 -35
  30. package/src/cfetch/index.ts +111 -0
  31. package/src/cfetch/internal.ts +72 -0
  32. package/src/cli.ts +6 -7
  33. package/src/config.ts +630 -85
  34. package/src/dev.tsx +446 -282
  35. package/src/dialogs.tsx +6 -14
  36. package/src/index.tsx +724 -418
  37. package/src/inspect.ts +596 -0
  38. package/src/kv.tsx +110 -45
  39. package/src/module-collection.ts +63 -0
  40. package/src/npm-installer.ts +20 -0
  41. package/src/pages.tsx +916 -211
  42. package/src/paths.ts +26 -0
  43. package/src/proxy.ts +370 -0
  44. package/src/publish.ts +219 -87
  45. package/src/sites.tsx +180 -55
  46. package/src/tail.tsx +6 -4
  47. package/src/user.tsx +77 -87
  48. package/src/whoami.tsx +69 -0
  49. package/wrangler-dist/cli.js +125169 -557
  50. package/wrangler-dist/cli.js.map +3 -3
  51. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  52. package/src/__tests__/mock-cfetch.js +0 -46
  53. package/src/api/inspect.ts +0 -441
  54. package/src/cfetch.ts +0 -72
  55. package/src/util/fetch.ts +0 -74
@@ -0,0 +1,40 @@
1
+ import { createFetchResult, setMockRawResponse } from "./mock-cfetch";
2
+
3
+ export function mockKeyListRequest(
4
+ expectedNamespaceId: string,
5
+ expectedKeys: string[],
6
+ keysPerRequest = 1000,
7
+ blankCursorValue: "" | undefined | null = undefined
8
+ ) {
9
+ const requests = { count: 0 };
10
+ // See https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
11
+ const expectedKeyObjects = expectedKeys.map((name) => ({
12
+ name,
13
+ expiration: 123456789,
14
+ metadata: {},
15
+ }));
16
+ setMockRawResponse(
17
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId/keys",
18
+ "GET",
19
+ ([_url, accountId, namespaceId], _init, query) => {
20
+ requests.count++;
21
+ expect(accountId).toEqual("some-account-id");
22
+ expect(namespaceId).toEqual(expectedNamespaceId);
23
+ if (expectedKeyObjects.length <= keysPerRequest) {
24
+ return createFetchResult(expectedKeyObjects);
25
+ } else {
26
+ const start = parseInt(query.get("cursor") ?? "0") || 0;
27
+ const end = start + keysPerRequest;
28
+ const cursor = end < expectedKeyObjects.length ? end : blankCursorValue;
29
+ return createFetchResult(
30
+ expectedKeyObjects.slice(start, end),
31
+ true,
32
+ [],
33
+ [],
34
+ { cursor }
35
+ );
36
+ }
37
+ }
38
+ );
39
+ return requests;
40
+ }
@@ -0,0 +1,27 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ export function writeUserConfig(
6
+ oauth_token?: string,
7
+ refresh_token?: string,
8
+ expiration_time?: string
9
+ ) {
10
+ const lines: string[] = [];
11
+ if (oauth_token) {
12
+ lines.push(`oauth_token = "${oauth_token}"`);
13
+ }
14
+ if (refresh_token) {
15
+ lines.push(`refresh_token = "${refresh_token}"`);
16
+ }
17
+ if (expiration_time) {
18
+ lines.push(`expiration_time = "${expiration_time}"`);
19
+ }
20
+ const configPath = path.join(os.homedir(), ".wrangler/config");
21
+ mkdirSync(configPath, { recursive: true });
22
+ writeFileSync(
23
+ path.join(configPath, "default.toml"),
24
+ lines.join("\n"),
25
+ "utf-8"
26
+ );
27
+ }
@@ -0,0 +1,29 @@
1
+ import * as fs from "node:fs";
2
+ import os from "node:os";
3
+ import * as path from "node:path";
4
+
5
+ const originalCwd = process.cwd();
6
+
7
+ export function runInTempDir({ homedir }: { homedir?: string } = {}) {
8
+ let tmpDir: string;
9
+
10
+ beforeEach(() => {
11
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrangler-tests"));
12
+ process.chdir(tmpDir);
13
+ if (homedir !== undefined) {
14
+ // Override where the home directory is so that we can write our own user config,
15
+ // without destroying the real thing.
16
+ fs.mkdirSync(homedir);
17
+ // Note it is very important that we use the "default" value from "node:os" (e.g. `import os from "node:os";`)
18
+ // rather than an alias to the module (e.g. `import * as os from "node:os";`).
19
+ // This is because the module gets transpiled so that the "method" `homedir()` gets converted to a
20
+ // getter that is not configurable (and so cannot be spied upon).
21
+ jest.spyOn(os, "homedir").mockReturnValue(homedir);
22
+ }
23
+ });
24
+
25
+ afterEach(() => {
26
+ process.chdir(originalCwd);
27
+ fs.rmSync(tmpDir, { recursive: true });
28
+ });
29
+ }
@@ -0,0 +1,14 @@
1
+ import { main } from "../../index";
2
+ import { normalizeSlashes, stripTimings } from "./mock-console";
3
+
4
+ /**
5
+ * A helper to 'run' wrangler commands for tests.
6
+ */
7
+ export async function runWrangler(cmd?: string) {
8
+ try {
9
+ await main(cmd?.split(" ") ?? []);
10
+ } catch (e) {
11
+ e.message = normalizeSlashes(stripTimings(e.message));
12
+ throw e;
13
+ }
14
+ }
@@ -1,153 +1,406 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as fsp from "node:fs/promises";
3
- import * as path from "node:path";
4
3
  import * as TOML from "@iarna/toml";
5
- import { main } from "../index";
6
- // @ts-expect-error we're mocking cfetch, so of course setMock isn't a thing
7
- import { setMock, unsetAllMocks } from "../cfetch";
8
-
9
- jest.mock("../cfetch", () => {
10
- return jest.requireActual("./mock-cfetch");
11
- });
12
-
13
- async function w(cmd: void | string, options?: { tap: boolean }) {
14
- const tapped = options?.tap ? tap() : undefined;
15
- await main([...(cmd ? cmd.split(" ") : [])]);
16
- tapped?.off();
17
- return { stdout: tapped?.out, stderr: tapped?.err };
18
- }
19
-
20
- function tap() {
21
- const oldLog = console.log;
22
- const oldError = console.error;
23
-
24
- const toReturn = {
25
- off: () => {
26
- console.log = oldLog;
27
- console.error = oldError;
28
- },
29
- out: "",
30
- err: "",
31
- };
32
-
33
- console.log = (...args) => {
34
- toReturn.out += args.join("");
35
- oldLog.apply(console, args);
36
- // console.trace(...args); // use this if you want to find the true source of your console.log
37
- };
38
- console.error = (...args) => {
39
- toReturn.err += args.join("");
40
- oldError.apply(console, args);
41
- };
42
-
43
- return toReturn;
44
- }
4
+ import { version as wranglerVersion } from "../../package.json";
5
+ import { npm } from "../npm-installer";
6
+ import { mockConsoleMethods } from "./helpers/mock-console";
7
+ import { mockConfirm } from "./helpers/mock-dialogs";
8
+ import { runInTempDir } from "./helpers/run-in-tmp";
9
+ import { runWrangler } from "./helpers/run-wrangler";
45
10
 
46
11
  describe("wrangler", () => {
47
- it("should run", async () => {
48
- const { stdout } = await w(undefined, { tap: true });
49
-
50
- expect(stdout).toMatchInlineSnapshot(`
51
- "wrangler
52
-
53
- Commands:
54
- wrangler init [name] 📥 Create a wrangler.toml configuration file
55
- wrangler dev <filename> 👂 Start a local server for developing your worker
56
- wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
57
- wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
58
- wrangler secret 🤫 Generate a secret that can be referenced in the worker script
59
- wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
60
- wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
61
- wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
62
- wrangler pages ⚡️ Configure Cloudflare Pages
63
-
64
- Flags:
65
- --config Path to .toml configuration file [string]
66
- --help Show help [boolean]
67
- --version Show version number [boolean]
68
-
69
- Options:
70
- --local Run on my machine [boolean] [default: false]"
71
- `);
12
+ runInTempDir();
13
+
14
+ beforeEach(() => {
15
+ jest.spyOn(npm, "addDevDeps").mockResolvedValue();
16
+ jest.spyOn(npm, "install").mockResolvedValue();
72
17
  });
73
18
 
74
- describe("init", () => {
75
- const ogcwd = process.cwd();
19
+ const std = mockConsoleMethods();
20
+
21
+ describe("no command", () => {
22
+ it("should display a list of available commands", async () => {
23
+ await runWrangler();
76
24
 
77
- beforeEach(() => {
78
- process.chdir(path.join(__dirname, "fixtures", "init"));
25
+ expect(std.out).toMatchInlineSnapshot(`
26
+ "wrangler
27
+
28
+ Commands:
29
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
30
+ wrangler whoami 🕵️ Retrieve your user info and test your auth config
31
+ wrangler dev <filename> 👂 Start a local server for developing your worker
32
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
33
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
34
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
35
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
36
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
37
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
38
+ wrangler pages ⚡️ Configure Cloudflare Pages
39
+
40
+ Flags:
41
+ -c, --config Path to .toml configuration file [string]
42
+ -h, --help Show help [boolean]
43
+ -v, --version Show version number [boolean]
44
+
45
+ Options:
46
+ -l, --local Run on my machine [boolean] [default: false]"
47
+ `);
48
+
49
+ expect(std.err).toMatchInlineSnapshot(`""`);
79
50
  });
51
+ });
80
52
 
81
- afterEach(async () => {
82
- await fsp.rm("./wrangler.toml");
83
- process.chdir(ogcwd);
53
+ describe("invalid command", () => {
54
+ it("should display an error", async () => {
55
+ await expect(
56
+ runWrangler("invalid-command")
57
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
58
+ `"Unknown command: invalid-command."`
59
+ );
60
+
61
+ expect(std.out).toMatchInlineSnapshot(`""`);
62
+ expect(std.err).toMatchInlineSnapshot(`
63
+ "wrangler
64
+
65
+ Commands:
66
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
67
+ wrangler whoami 🕵️ Retrieve your user info and test your auth config
68
+ wrangler dev <filename> 👂 Start a local server for developing your worker
69
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
70
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
71
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
72
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
73
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
74
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
75
+ wrangler pages ⚡️ Configure Cloudflare Pages
76
+
77
+ Flags:
78
+ -c, --config Path to .toml configuration file [string]
79
+ -h, --help Show help [boolean]
80
+ -v, --version Show version number [boolean]
81
+
82
+ Options:
83
+ -l, --local Run on my machine [boolean] [default: false]
84
+
85
+ Unknown command: invalid-command."
86
+ `);
84
87
  });
88
+ });
85
89
 
90
+ describe("init", () => {
86
91
  it("should create a wrangler.toml", async () => {
87
- await w("init");
92
+ mockConfirm({
93
+ text: "No package.json found. Would you like to create one?",
94
+ result: false,
95
+ });
96
+ await runWrangler("init");
88
97
  const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
89
98
  expect(typeof parsed.compatibility_date).toBe("string");
99
+ expect(fs.existsSync("./package.json")).toBe(false);
100
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
90
101
  });
91
102
 
92
- it("should error when wrangler.toml already exists", async () => {
93
- fs.closeSync(fs.openSync("./wrangler.toml", "w"));
94
- const { stderr } = await w("init", { tap: true });
95
- expect(stderr.endsWith("wrangler.toml already exists.")).toBe(true);
103
+ it("should display warning when wrangler.toml already exists, and exit if user does not want to carry on", async () => {
104
+ fs.writeFileSync(
105
+ "./wrangler.toml",
106
+ 'compatibility_date="something-else"', // use a fake value to make sure the file is not overwritten
107
+ "utf-8"
108
+ );
109
+ mockConfirm({
110
+ text: "Do you want to continue initializing this project?",
111
+ result: false,
112
+ });
113
+ await runWrangler("init");
114
+ expect(std.warn).toContain("wrangler.toml file already exists!");
115
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
116
+ expect(parsed.compatibility_date).toBe("something-else");
96
117
  });
97
- });
98
118
 
99
- describe("kv:namespace", () => {
100
- afterAll(() => {
101
- unsetAllMocks();
102
- });
103
- let KVNamespaces: { title: string; id: string }[] = [];
104
- it("can create a namespace", async () => {
105
- setMock("/accounts/:accountId/storage/kv/namespaces", (uri, init) => {
106
- expect(init.method === "POST");
107
- const body = JSON.parse(init.body);
108
- expect(body.title).toBe("worker-UnitTestNamespace");
109
- KVNamespaces.push({ title: body.title, id: "some-namespace-id" });
110
- return { id: "some-namespace-id" };
119
+ it("should display warning when wrangler.toml already exists, but continue if user does want to carry on", async () => {
120
+ fs.writeFileSync(
121
+ "./wrangler.toml",
122
+ `compatibility_date="something-else"`,
123
+ "utf-8"
124
+ );
125
+ mockConfirm(
126
+ {
127
+ text: "Do you want to continue initializing this project?",
128
+ result: true,
129
+ },
130
+ {
131
+ text: "No package.json found. Would you like to create one?",
132
+ result: false,
133
+ }
134
+ );
135
+ await runWrangler("init");
136
+ expect(std.warn).toContain("wrangler.toml file already exists!");
137
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
138
+ expect(parsed.compatibility_date).toBe("something-else");
139
+ });
140
+
141
+ it("should create a package.json if none is found and user confirms", async () => {
142
+ mockConfirm(
143
+ {
144
+ text: "No package.json found. Would you like to create one?",
145
+ result: true,
146
+ },
147
+ {
148
+ text: "Would you like to use typescript?",
149
+ result: false,
150
+ }
151
+ );
152
+ await runWrangler("init");
153
+ expect(fs.existsSync("./package.json")).toBe(true);
154
+ const packageJson = JSON.parse(
155
+ fs.readFileSync("./package.json", "utf-8")
156
+ );
157
+ expect(packageJson.name).toEqual("worker"); // TODO: should we infer the name from the directory?
158
+ expect(packageJson.version).toEqual("0.0.0");
159
+ expect(packageJson.devDependencies).toEqual({
160
+ wrangler: expect.any(String),
111
161
  });
162
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
163
+ expect(npm.install).toHaveBeenCalled();
164
+ });
112
165
 
113
- await w('kv:namespace create "UnitTestNamespace"');
114
- expect(
115
- KVNamespaces.find((ns) => ns.title === `worker-UnitTestNamespace`)
116
- ).toBeTruthy();
166
+ it("should not touch an existing package.json in the same directory", async () => {
167
+ mockConfirm(
168
+ {
169
+ text: "Would you like to install wrangler into your package.json?",
170
+ result: false,
171
+ },
172
+ {
173
+ text: "Would you like to use typescript?",
174
+ result: false,
175
+ }
176
+ );
177
+
178
+ fs.writeFileSync(
179
+ "./package.json",
180
+ JSON.stringify({ name: "test", version: "1.0.0" }),
181
+ "utf-8"
182
+ );
183
+
184
+ await runWrangler("init");
185
+ const packageJson = JSON.parse(
186
+ fs.readFileSync("./package.json", "utf-8")
187
+ );
188
+ expect(packageJson.name).toEqual("test");
189
+ expect(packageJson.version).toEqual("1.0.0");
117
190
  });
118
191
 
119
- let createdNamespace: { id: string; title: string };
120
- it("can list namespaces", async () => {
121
- setMock(
122
- "/accounts/:accountId/storage/kv/namespaces\\?:qs",
123
- (uri, init) => {
124
- expect(init).toBe(undefined);
125
- return KVNamespaces;
192
+ it("should offer to install wrangler into an existing package.json", async () => {
193
+ mockConfirm(
194
+ {
195
+ text: "Would you like to install wrangler into your package.json?",
196
+ result: true,
197
+ },
198
+ {
199
+ text: "Would you like to use typescript?",
200
+ result: false,
126
201
  }
127
202
  );
128
- const { stdout } = await w("kv:namespace list", { tap: true });
129
- const namespaces = JSON.parse(stdout);
130
- createdNamespace = namespaces.find(
131
- (ns) => ns.title === "worker-UnitTestNamespace"
203
+
204
+ fs.writeFileSync(
205
+ "./package.json",
206
+ JSON.stringify({ name: "test", version: "1.0.0" }),
207
+ "utf-8"
208
+ );
209
+
210
+ await runWrangler("init");
211
+ const packageJson = JSON.parse(
212
+ fs.readFileSync("./package.json", "utf-8")
213
+ );
214
+ expect(packageJson.name).toEqual("test");
215
+ expect(packageJson.version).toEqual("1.0.0");
216
+ expect(npm.addDevDeps).toHaveBeenCalledWith(
217
+ `wrangler@${wranglerVersion}`
132
218
  );
133
- expect(createdNamespace.title).toBe("worker-UnitTestNamespace");
134
219
  });
135
220
 
136
- it("can delete a namespace", async () => {
137
- const namespaceIdToDelete = createdNamespace.id;
138
- setMock(
139
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId",
140
- (uri, init) => {
141
- expect(init.method).toBe("DELETE");
142
- KVNamespaces = KVNamespaces.filter(
143
- (ns) => ns.id !== namespaceIdToDelete
144
- );
221
+ it("should not touch an existing package.json in an ancestor directory", async () => {
222
+ mockConfirm(
223
+ {
224
+ text: "Would you like to install wrangler into your package.json?",
225
+ result: false,
226
+ },
227
+ {
228
+ text: "Would you like to use typescript?",
229
+ result: false,
145
230
  }
146
231
  );
147
- await w(`kv:namespace delete --namespace-id ${namespaceIdToDelete}`);
148
- expect(KVNamespaces.find((ns) => ns.id === namespaceIdToDelete)).toBe(
149
- undefined
232
+
233
+ fs.writeFileSync(
234
+ "./package.json",
235
+ JSON.stringify({ name: "test", version: "1.0.0" }),
236
+ "utf-8"
150
237
  );
238
+
239
+ fs.mkdirSync("./sub-1/sub-2", { recursive: true });
240
+ process.chdir("./sub-1/sub-2");
241
+
242
+ await runWrangler("init");
243
+ expect(fs.existsSync("./package.json")).toBe(false);
244
+ expect(fs.existsSync("../../package.json")).toBe(true);
245
+
246
+ const packageJson = JSON.parse(
247
+ fs.readFileSync("../../package.json", "utf-8")
248
+ );
249
+ expect(packageJson).toMatchInlineSnapshot(`
250
+ Object {
251
+ "name": "test",
252
+ "version": "1.0.0",
253
+ }
254
+ `);
255
+ });
256
+
257
+ it("should create a tsconfig.json and install `workers-types` if none is found and user confirms", async () => {
258
+ mockConfirm(
259
+ {
260
+ text: "No package.json found. Would you like to create one?",
261
+ result: true,
262
+ },
263
+ {
264
+ text: "Would you like to use typescript?",
265
+ result: true,
266
+ }
267
+ );
268
+ await runWrangler("init");
269
+ expect(fs.existsSync("./tsconfig.json")).toBe(true);
270
+ const tsconfigJson = JSON.parse(
271
+ fs.readFileSync("./tsconfig.json", "utf-8")
272
+ );
273
+ expect(tsconfigJson.compilerOptions.types).toEqual([
274
+ "@cloudflare/workers-types",
275
+ ]);
276
+ expect(npm.addDevDeps).toHaveBeenCalledWith(
277
+ "@cloudflare/workers-types",
278
+ "typescript"
279
+ );
280
+ });
281
+
282
+ it("should not touch an existing tsconfig.json in the same directory", async () => {
283
+ fs.writeFileSync(
284
+ "./package.json",
285
+ JSON.stringify({
286
+ name: "test",
287
+ version: "1.0.0",
288
+ devDependencies: {
289
+ wrangler: "0.0.0",
290
+ "@cloudflare/workers-types": "0.0.0",
291
+ },
292
+ }),
293
+ "utf-8"
294
+ );
295
+ fs.writeFileSync(
296
+ "./tsconfig.json",
297
+ JSON.stringify({ compilerOptions: {} }),
298
+ "utf-8"
299
+ );
300
+
301
+ await runWrangler("init");
302
+ const tsconfigJson = JSON.parse(
303
+ fs.readFileSync("./tsconfig.json", "utf-8")
304
+ );
305
+ expect(tsconfigJson.compilerOptions).toEqual({});
306
+ });
307
+
308
+ it("should offer to install type definitions in an existing typescript project", async () => {
309
+ mockConfirm(
310
+ {
311
+ text: "Would you like to install wrangler into your package.json?",
312
+ result: false,
313
+ },
314
+ {
315
+ text: "Would you like to install the type definitions for Workers into your package.json?",
316
+ result: true,
317
+ }
318
+ );
319
+ fs.writeFileSync(
320
+ "./package.json",
321
+ JSON.stringify({
322
+ name: "test",
323
+ version: "1.0.0",
324
+ }),
325
+ "utf-8"
326
+ );
327
+ fs.writeFileSync(
328
+ "./tsconfig.json",
329
+ JSON.stringify({ compilerOptions: {} }),
330
+ "utf-8"
331
+ );
332
+
333
+ await runWrangler("init");
334
+ const tsconfigJson = JSON.parse(
335
+ fs.readFileSync("./tsconfig.json", "utf-8")
336
+ );
337
+ // unchanged tsconfig
338
+ expect(tsconfigJson.compilerOptions).toEqual({});
339
+ expect(npm.addDevDeps).toHaveBeenCalledWith("@cloudflare/workers-types");
340
+ });
341
+
342
+ it("should not touch an existing tsconfig.json in an ancestor directory", async () => {
343
+ fs.writeFileSync(
344
+ "./package.json",
345
+ JSON.stringify({
346
+ name: "test",
347
+ version: "1.0.0",
348
+ devDependencies: {
349
+ wrangler: "0.0.0",
350
+ "@cloudflare/workers-types": "0.0.0",
351
+ },
352
+ }),
353
+ "utf-8"
354
+ );
355
+ fs.writeFileSync(
356
+ "./tsconfig.json",
357
+ JSON.stringify({ compilerOptions: {} }),
358
+ "utf-8"
359
+ );
360
+
361
+ fs.mkdirSync("./sub-1/sub-2", { recursive: true });
362
+ process.chdir("./sub-1/sub-2");
363
+
364
+ await runWrangler("init");
365
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
366
+ expect(fs.existsSync("../../tsconfig.json")).toBe(true);
367
+
368
+ const tsconfigJson = JSON.parse(
369
+ fs.readFileSync("../../tsconfig.json", "utf-8")
370
+ );
371
+ expect(tsconfigJson.compilerOptions).toEqual({});
372
+ });
373
+
374
+ it("should error if `--type` is used", async () => {
375
+ await expect(
376
+ runWrangler("init --type")
377
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
378
+ `"The --type option is no longer supported."`
379
+ );
380
+ });
381
+
382
+ it("should error if `--type javascript` is used", async () => {
383
+ await expect(
384
+ runWrangler("init --type javascript")
385
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
386
+ `"The --type option is no longer supported."`
387
+ );
388
+ });
389
+
390
+ it("should error if `--type rust` is used", async () => {
391
+ await expect(
392
+ runWrangler("init --type rust")
393
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
394
+ `"The --type option is no longer supported."`
395
+ );
396
+ });
397
+
398
+ it("should error if `--type webpack` is used", async () => {
399
+ await expect(runWrangler("init --type webpack")).rejects
400
+ .toThrowErrorMatchingInlineSnapshot(`
401
+ "The --type option is no longer supported.
402
+ If you wish to use webpack then you will need to create a custom build."
403
+ `);
151
404
  });
152
405
  });
153
406
  });
@@ -0,0 +1,34 @@
1
+ import fetchMock from "jest-fetch-mock";
2
+ import { fetchInternal } from "../cfetch/internal";
3
+ import { confirm, prompt } from "../dialogs";
4
+ import { mockFetchInternal } from "./helpers/mock-cfetch";
5
+
6
+ jest.mock("undici", () => {
7
+ return {
8
+ ...jest.requireActual("undici"),
9
+ fetch: jest.requireActual("jest-fetch-mock"),
10
+ };
11
+ });
12
+ fetchMock.doMock(() => {
13
+ // Any un-mocked fetches should throw
14
+ throw new Error("Unexpected fetch request");
15
+ });
16
+
17
+ jest.mock("../cfetch/internal");
18
+ (fetchInternal as jest.Mock).mockImplementation(mockFetchInternal);
19
+
20
+ jest.mock("../dialogs");
21
+
22
+ // By default (if not configured by mockConfirm()) calls to `confirm()` should throw.
23
+ (confirm as jest.Mock).mockImplementation(() => {
24
+ throw new Error(
25
+ "Unexpected call to `confirm()`. You should use `mockConfirm()` to mock calls to `confirm()` with expectations. Search the codebase for `mockConfirm` to learn more."
26
+ );
27
+ });
28
+
29
+ // By default (if not configured by mockPrompt()) calls to `prompt()` should throw.
30
+ (prompt as jest.Mock).mockImplementation(() => {
31
+ throw new Error(
32
+ "Unexpected call to `prompt()`. You should use `mockPrompt()` to mock calls to `prompt()` with expectations. Search the codebase for `mockPrompt` to learn more."
33
+ );
34
+ });