wrangler 0.0.0-ece06ea → 0.0.0-ef13735

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 (63) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +35 -21
  3. package/pages/functions/buildWorker.ts +62 -0
  4. package/pages/functions/filepath-routing.test.ts +66 -0
  5. package/pages/functions/filepath-routing.ts +219 -0
  6. package/pages/functions/identifiers.ts +78 -0
  7. package/pages/functions/routes.ts +151 -0
  8. package/pages/functions/template-worker.ts +130 -0
  9. package/src/__tests__/dev.test.tsx +73 -0
  10. package/src/__tests__/guess-worker-format.test.ts +51 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  14. package/src/__tests__/helpers/mock-bin.ts +33 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  16. package/src/__tests__/helpers/mock-console.ts +56 -0
  17. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  18. package/src/__tests__/helpers/mock-kv.ts +40 -0
  19. package/src/__tests__/helpers/mock-user.ts +27 -0
  20. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  21. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  22. package/src/__tests__/index.test.ts +715 -119
  23. package/src/__tests__/jest.setup.ts +37 -0
  24. package/src/__tests__/kv.test.ts +1139 -0
  25. package/src/__tests__/logout.test.ts +50 -0
  26. package/src/__tests__/package-manager.test.ts +206 -0
  27. package/src/__tests__/publish.test.ts +1381 -0
  28. package/src/__tests__/secret.test.ts +210 -0
  29. package/src/__tests__/whoami.test.tsx +86 -0
  30. package/src/api/form_data.ts +93 -100
  31. package/src/api/preview.ts +29 -24
  32. package/src/api/worker.ts +55 -47
  33. package/src/cfetch/index.ts +102 -0
  34. package/src/cfetch/internal.ts +101 -0
  35. package/src/cli.ts +6 -7
  36. package/src/config.ts +641 -112
  37. package/src/dev.tsx +476 -355
  38. package/src/dialogs.tsx +6 -14
  39. package/src/guess-worker-format.ts +66 -0
  40. package/src/index.tsx +828 -496
  41. package/src/inspect.ts +596 -0
  42. package/src/kv.tsx +118 -45
  43. package/src/module-collection.ts +63 -0
  44. package/src/open-in-browser.ts +13 -0
  45. package/src/package-manager.ts +120 -0
  46. package/src/pages.tsx +915 -215
  47. package/src/paths.ts +26 -0
  48. package/src/proxy.ts +370 -0
  49. package/src/publish.ts +349 -290
  50. package/src/sites.tsx +184 -55
  51. package/src/tail.tsx +5 -3
  52. package/src/user.tsx +81 -91
  53. package/src/whoami.tsx +69 -0
  54. package/templates/new-worker.js +15 -0
  55. package/templates/new-worker.ts +15 -0
  56. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  57. package/wrangler-dist/cli.js +119231 -130682
  58. package/wrangler-dist/cli.js.map +3 -3
  59. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  60. package/src/__tests__/mock-cfetch.js +0 -46
  61. package/src/api/inspect.ts +0 -441
  62. package/src/cfetch.ts +0 -72
  63. package/src/util/fetch.ts +0 -74
@@ -1,153 +1,749 @@
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 { getPackageManager } from "../package-manager";
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";
10
+ import type { PackageManager } from "../package-manager";
45
11
 
46
12
  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
- `);
13
+ let mockPackageManager: PackageManager;
14
+ runInTempDir();
15
+
16
+ beforeEach(() => {
17
+ mockPackageManager = {
18
+ addDevDeps: jest.fn(),
19
+ install: jest.fn(),
20
+ };
21
+ (getPackageManager as jest.Mock).mockResolvedValue(mockPackageManager);
72
22
  });
73
23
 
74
- describe("init", () => {
75
- const ogcwd = process.cwd();
24
+ const std = mockConsoleMethods();
25
+
26
+ describe("no command", () => {
27
+ it("should display a list of available commands", async () => {
28
+ await runWrangler();
29
+
30
+ expect(std.out).toMatchInlineSnapshot(`
31
+ "wrangler
32
+
33
+ Commands:
34
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
35
+ wrangler whoami 🕵️ Retrieve your user info and test your auth config
36
+ wrangler dev <filename> 👂 Start a local server for developing your worker
37
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
38
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
39
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
40
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
41
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
42
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
43
+ wrangler pages ⚡️ Configure Cloudflare Pages
44
+
45
+ Flags:
46
+ -c, --config Path to .toml configuration file [string]
47
+ -h, --help Show help [boolean]
48
+ -v, --version Show version number [boolean]
49
+
50
+ Options:
51
+ -l, --local Run on my machine [boolean] [default: false]"
52
+ `);
76
53
 
77
- beforeEach(() => {
78
- process.chdir(path.join(__dirname, "fixtures", "init"));
54
+ expect(std.err).toMatchInlineSnapshot(`""`);
79
55
  });
56
+ });
57
+
58
+ describe("invalid command", () => {
59
+ it("should display an error", async () => {
60
+ await expect(
61
+ runWrangler("invalid-command")
62
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
63
+ `"Unknown command: invalid-command."`
64
+ );
65
+
66
+ expect(std.out).toMatchInlineSnapshot(`""`);
67
+ expect(std.err).toMatchInlineSnapshot(`
68
+ "wrangler
69
+
70
+ Commands:
71
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
72
+ wrangler whoami 🕵️ Retrieve your user info and test your auth config
73
+ wrangler dev <filename> 👂 Start a local server for developing your worker
74
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
75
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
76
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
77
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
78
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
79
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
80
+ wrangler pages ⚡️ Configure Cloudflare Pages
80
81
 
81
- afterEach(async () => {
82
- await fsp.rm("./wrangler.toml");
83
- process.chdir(ogcwd);
82
+ Flags:
83
+ -c, --config Path to .toml configuration file [string]
84
+ -h, --help Show help [boolean]
85
+ -v, --version Show version number [boolean]
86
+
87
+ Options:
88
+ -l, --local Run on my machine [boolean] [default: false]
89
+
90
+ Unknown command: invalid-command."
91
+ `);
84
92
  });
93
+ });
85
94
 
95
+ describe("init", () => {
86
96
  it("should create a wrangler.toml", async () => {
87
- await w("init");
97
+ mockConfirm({
98
+ text: "No package.json found. Would you like to create one?",
99
+ result: false,
100
+ });
101
+ await runWrangler("init");
88
102
  const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
89
103
  expect(typeof parsed.compatibility_date).toBe("string");
104
+ expect(parsed.name).toContain("wrangler-tests");
105
+ expect(fs.existsSync("./package.json")).toBe(false);
106
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
90
107
  });
91
108
 
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);
109
+ it("should create a named Worker wrangler.toml", async () => {
110
+ mockConfirm({
111
+ text: "No package.json found. Would you like to create one?",
112
+ result: false,
113
+ });
114
+ await runWrangler("init my-worker");
115
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
116
+ expect(typeof parsed.compatibility_date).toBe("string");
117
+ expect(parsed.name).toBe("my-worker");
118
+ expect(fs.existsSync("./package.json")).toBe(false);
119
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
120
+ });
121
+
122
+ it("should display warning when wrangler.toml already exists, and exit if user does not want to carry on", async () => {
123
+ fs.writeFileSync(
124
+ "./wrangler.toml",
125
+ 'compatibility_date="something-else"', // use a fake value to make sure the file is not overwritten
126
+ "utf-8"
127
+ );
128
+ mockConfirm({
129
+ text: "Do you want to continue initializing this project?",
130
+ result: false,
131
+ });
132
+ await runWrangler("init");
133
+ expect(std.warn).toContain("wrangler.toml file already exists!");
134
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
135
+ expect(parsed.compatibility_date).toBe("something-else");
136
+ });
137
+
138
+ it("should display warning when wrangler.toml already exists, but continue if user does want to carry on", async () => {
139
+ fs.writeFileSync(
140
+ "./wrangler.toml",
141
+ `compatibility_date="something-else"`,
142
+ "utf-8"
143
+ );
144
+ mockConfirm(
145
+ {
146
+ text: "Do you want to continue initializing this project?",
147
+ result: true,
148
+ },
149
+ {
150
+ text: "No package.json found. Would you like to create one?",
151
+ result: false,
152
+ }
153
+ );
154
+ await runWrangler("init");
155
+ expect(std.warn).toContain("wrangler.toml file already exists!");
156
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
157
+ expect(parsed.compatibility_date).toBe("something-else");
96
158
  });
97
- });
98
159
 
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" };
160
+ it("should create a package.json if none is found and user confirms", async () => {
161
+ mockConfirm(
162
+ {
163
+ text: "No package.json found. Would you like to create one?",
164
+ result: true,
165
+ },
166
+ {
167
+ text: "Would you like to use TypeScript?",
168
+ result: false,
169
+ },
170
+ {
171
+ text: "Would you like to create a Worker at src/index.js?",
172
+ result: false,
173
+ }
174
+ );
175
+ await runWrangler("init");
176
+ expect(fs.existsSync("./package.json")).toBe(true);
177
+ const packageJson = JSON.parse(
178
+ fs.readFileSync("./package.json", "utf-8")
179
+ );
180
+ expect(packageJson.name).toContain("wrangler-tests");
181
+ expect(packageJson.version).toEqual("0.0.0");
182
+ expect(packageJson.devDependencies).toEqual({
183
+ wrangler: expect.any(String),
111
184
  });
185
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
186
+ expect(mockPackageManager.install).toHaveBeenCalled();
187
+ });
188
+
189
+ it("should create a package.json, with the specified name, if none is found and user confirms", async () => {
190
+ mockConfirm(
191
+ {
192
+ text: "No package.json found. Would you like to create one?",
193
+ result: true,
194
+ },
195
+ {
196
+ text: "Would you like to use TypeScript?",
197
+ result: false,
198
+ },
199
+ {
200
+ text: "Would you like to create a Worker at src/index.js?",
201
+ result: false,
202
+ }
203
+ );
204
+ await runWrangler("init my-worker");
205
+ const packageJson = JSON.parse(
206
+ fs.readFileSync("./package.json", "utf-8")
207
+ );
208
+ expect(packageJson.name).toBe("my-worker");
209
+ });
210
+
211
+ it("should not touch an existing package.json in the same directory", async () => {
212
+ mockConfirm(
213
+ {
214
+ text: "Would you like to install wrangler into your package.json?",
215
+ result: false,
216
+ },
217
+ {
218
+ text: "Would you like to use TypeScript?",
219
+ result: false,
220
+ },
221
+ {
222
+ text: "Would you like to create a Worker at src/index.js?",
223
+ result: false,
224
+ }
225
+ );
226
+
227
+ fs.writeFileSync(
228
+ "./package.json",
229
+ JSON.stringify({ name: "test", version: "1.0.0" }),
230
+ "utf-8"
231
+ );
232
+
233
+ await runWrangler("init");
234
+ const packageJson = JSON.parse(
235
+ fs.readFileSync("./package.json", "utf-8")
236
+ );
237
+ expect(packageJson.name).toEqual("test");
238
+ expect(packageJson.version).toEqual("1.0.0");
239
+ });
240
+
241
+ it("should offer to install wrangler into an existing package.json", async () => {
242
+ mockConfirm(
243
+ {
244
+ text: "Would you like to install wrangler into your package.json?",
245
+ result: true,
246
+ },
247
+ {
248
+ text: "Would you like to use TypeScript?",
249
+ result: false,
250
+ },
251
+ {
252
+ text: "Would you like to create a Worker at src/index.js?",
253
+ result: false,
254
+ }
255
+ );
256
+
257
+ fs.writeFileSync(
258
+ "./package.json",
259
+ JSON.stringify({ name: "test", version: "1.0.0" }),
260
+ "utf-8"
261
+ );
262
+
263
+ await runWrangler("init");
264
+ const packageJson = JSON.parse(
265
+ fs.readFileSync("./package.json", "utf-8")
266
+ );
267
+ expect(packageJson.name).toEqual("test");
268
+ expect(packageJson.version).toEqual("1.0.0");
269
+ expect(mockPackageManager.addDevDeps).toHaveBeenCalledWith(
270
+ `wrangler@${wranglerVersion}`
271
+ );
272
+ });
273
+
274
+ it("should not touch an existing package.json in an ancestor directory", async () => {
275
+ mockConfirm(
276
+ {
277
+ text: "Would you like to install wrangler into your package.json?",
278
+ result: false,
279
+ },
280
+ {
281
+ text: "Would you like to use TypeScript?",
282
+ result: false,
283
+ },
284
+ {
285
+ text: "Would you like to create a Worker at src/index.js?",
286
+ result: false,
287
+ }
288
+ );
289
+
290
+ fs.writeFileSync(
291
+ "./package.json",
292
+ JSON.stringify({ name: "test", version: "1.0.0" }),
293
+ "utf-8"
294
+ );
295
+
296
+ fs.mkdirSync("./sub-1/sub-2", { recursive: true });
297
+ process.chdir("./sub-1/sub-2");
298
+
299
+ await runWrangler("init");
300
+ expect(fs.existsSync("./package.json")).toBe(false);
301
+ expect(fs.existsSync("../../package.json")).toBe(true);
302
+
303
+ const packageJson = JSON.parse(
304
+ fs.readFileSync("../../package.json", "utf-8")
305
+ );
306
+ expect(packageJson).toMatchInlineSnapshot(`
307
+ Object {
308
+ "name": "test",
309
+ "version": "1.0.0",
310
+ }
311
+ `);
312
+ });
313
+
314
+ it("should offer to create a worker in a non-typescript project", async () => {
315
+ mockConfirm(
316
+ {
317
+ text: "Would you like to install wrangler into your package.json?",
318
+ result: false,
319
+ },
320
+ {
321
+ text: "Would you like to use TypeScript?",
322
+ result: false,
323
+ },
324
+ {
325
+ text: "Would you like to create a Worker at src/index.js?",
326
+ result: true,
327
+ }
328
+ );
329
+
330
+ fs.writeFileSync(
331
+ "./package.json",
332
+ JSON.stringify({ name: "test", version: "1.0.0" }),
333
+ "utf-8"
334
+ );
335
+
336
+ await runWrangler("init");
337
+ expect(fs.existsSync("./src/index.js")).toBe(true);
338
+ expect(fs.existsSync("./src/index.ts")).toBe(false);
339
+ });
340
+
341
+ it("should offer to create a worker in a typescript project", async () => {
342
+ mockConfirm(
343
+ {
344
+ text: "Would you like to install wrangler into your package.json?",
345
+ result: false,
346
+ },
347
+ {
348
+ text: "Would you like to use TypeScript?",
349
+ result: true,
350
+ },
351
+ {
352
+ text: "Would you like to create a Worker at src/index.ts?",
353
+ result: true,
354
+ }
355
+ );
356
+
357
+ fs.writeFileSync(
358
+ "./package.json",
359
+ JSON.stringify({ name: "test", version: "1.0.0" }),
360
+ "utf-8"
361
+ );
362
+
363
+ await runWrangler("init");
364
+ expect(fs.existsSync("./src/index.js")).toBe(false);
365
+ expect(fs.existsSync("./src/index.ts")).toBe(true);
366
+ });
367
+
368
+ it("should add scripts for a typescript project with .ts extension", async () => {
369
+ mockConfirm(
370
+ {
371
+ text: "No package.json found. Would you like to create one?",
372
+ result: true,
373
+ },
374
+ {
375
+ text: "Would you like to install wrangler into your package.json?",
376
+ result: false,
377
+ },
378
+ {
379
+ text: "Would you like to use TypeScript?",
380
+ result: true,
381
+ },
382
+ {
383
+ text: "Would you like to create a Worker at src/index.ts?",
384
+ result: true,
385
+ }
386
+ );
387
+ await runWrangler("init");
388
+
389
+ expect(fs.existsSync("./package.json")).toBe(true);
390
+ const packageJson = JSON.parse(
391
+ fs.readFileSync("./package.json", "utf-8")
392
+ );
393
+
394
+ expect(fs.existsSync("./src/index.js")).toBe(false);
395
+ expect(fs.existsSync("./src/index.ts")).toBe(true);
396
+
397
+ expect(packageJson.scripts.start).toBe("wrangler dev src/index.ts");
398
+ expect(packageJson.scripts.deploy).toBe("wrangler publish src/index.ts");
399
+ expect(packageJson.name).toContain("wrangler-tests");
400
+ expect(packageJson.version).toEqual("0.0.0");
401
+ expect(std.out).toMatchInlineSnapshot(`
402
+ "✨ Successfully created wrangler.toml
403
+ ✨ Created package.json
404
+ ✨ Created tsconfig.json, installed @cloudflare/workers-types into devDependencies
405
+ To start developing on your worker, run npm start.
406
+ To publish your worker on to the internet, run npm run deploy.
407
+ ✨ Created src/index.ts"
408
+ `);
409
+ });
410
+
411
+ it("should not overwrite package.json scripts for a typescript project", async () => {
412
+ mockConfirm(
413
+ {
414
+ text: "Would you like to install wrangler into your package.json?",
415
+ result: false,
416
+ },
417
+ {
418
+ text: "Would you like to use TypeScript?",
419
+ result: true,
420
+ },
421
+ {
422
+ text: "Would you like to create a Worker at src/index.ts?",
423
+ result: true,
424
+ }
425
+ );
426
+ await fsp.writeFile(
427
+ "./package.json",
428
+ JSON.stringify({
429
+ scripts: {
430
+ start: "test-start",
431
+ deploy: "test-deploy",
432
+ },
433
+ })
434
+ );
435
+ const packageJson = JSON.parse(
436
+ fs.readFileSync("./package.json", "utf-8")
437
+ );
438
+ await runWrangler("init");
439
+
440
+ expect(fs.existsSync("./src/index.js")).toBe(false);
441
+ expect(fs.existsSync("./src/index.ts")).toBe(true);
442
+
443
+ expect(packageJson.scripts.start).toBe("test-start");
444
+ expect(packageJson.scripts.deploy).toBe("test-deploy");
445
+ expect(std.out).toMatchInlineSnapshot(`
446
+ "✨ Successfully created wrangler.toml
447
+ ✨ Created tsconfig.json, installed @cloudflare/workers-types into devDependencies
448
+ To start developing on your worker, npx wrangler dev src/index.ts
449
+ To publish your worker on to the internet, npx wrangler publish src/index.ts
450
+ ✨ Created src/index.ts"
451
+ `);
452
+ });
453
+
454
+ it("should add missing scripts for a non-ts project with .js extension", async () => {
455
+ mockConfirm(
456
+ {
457
+ text: "No package.json found. Would you like to create one?",
458
+ result: true,
459
+ },
460
+ {
461
+ text: "Would you like to install wrangler into your package.json?",
462
+ result: false,
463
+ },
464
+ {
465
+ text: "Would you like to use TypeScript?",
466
+ result: false,
467
+ },
468
+ {
469
+ text: "Would you like to create a Worker at src/index.js?",
470
+ result: true,
471
+ }
472
+ );
473
+ await runWrangler("init");
474
+
475
+ expect(fs.existsSync("./package.json")).toBe(true);
476
+ const packageJson = JSON.parse(
477
+ fs.readFileSync("./package.json", "utf-8")
478
+ );
479
+
480
+ expect(fs.existsSync("./src/index.js")).toBe(true);
481
+ expect(fs.existsSync("./src/index.ts")).toBe(false);
482
+
483
+ expect(packageJson.scripts.start).toBe("wrangler dev src/index.js");
484
+ expect(packageJson.scripts.deploy).toBe("wrangler publish src/index.js");
485
+ expect(packageJson.name).toContain("wrangler-tests");
486
+ expect(packageJson.version).toEqual("0.0.0");
487
+ expect(std.out).toMatchInlineSnapshot(`
488
+ "✨ Successfully created wrangler.toml
489
+ ✨ Created package.json
490
+ To start developing on your worker, run npm start.
491
+ To publish your worker on to the internet, run npm run deploy.
492
+ ✨ Created src/index.js"
493
+ `);
494
+ });
495
+
496
+ it("should not overwrite package.json scripts for a non-ts project with .js extension", async () => {
497
+ mockConfirm(
498
+ {
499
+ text: "Would you like to install wrangler into your package.json?",
500
+ result: false,
501
+ },
502
+ {
503
+ text: "Would you like to use TypeScript?",
504
+ result: false,
505
+ },
506
+ {
507
+ text: "Would you like to create a Worker at src/index.js?",
508
+ result: true,
509
+ }
510
+ );
511
+ await fsp.writeFile(
512
+ "./package.json",
513
+ JSON.stringify({
514
+ scripts: {
515
+ start: "test-start",
516
+ deploy: "test-deploy",
517
+ },
518
+ })
519
+ );
520
+ const packageJson = JSON.parse(
521
+ fs.readFileSync("./package.json", "utf-8")
522
+ );
523
+ await runWrangler("init");
524
+
525
+ expect(fs.existsSync("./src/index.js")).toBe(true);
526
+ expect(fs.existsSync("./src/index.ts")).toBe(false);
527
+
528
+ expect(packageJson.scripts.start).toBe("test-start");
529
+ expect(packageJson.scripts.deploy).toBe("test-deploy");
530
+ expect(std.out).toMatchInlineSnapshot(`
531
+ "✨ Successfully created wrangler.toml
532
+ To start developing on your worker, npx wrangler dev src/index.js
533
+ To publish your worker on to the internet, npx wrangler publish src/index.js
534
+ ✨ Created src/index.js"
535
+ `);
536
+ });
537
+
538
+ it("should not offer to create a worker in a non-ts project if a file already exists at the location", async () => {
539
+ mockConfirm(
540
+ {
541
+ text: "Would you like to install wrangler into your package.json?",
542
+ result: false,
543
+ },
544
+ {
545
+ text: "Would you like to use TypeScript?",
546
+ result: false,
547
+ }
548
+ );
549
+
550
+ fs.writeFileSync(
551
+ "./package.json",
552
+ JSON.stringify({ name: "test", version: "1.0.0" }),
553
+ "utf-8"
554
+ );
555
+ fs.mkdirSync("./src", { recursive: true });
556
+ const PLACEHOLDER = "/* placeholder text */";
557
+ fs.writeFileSync("./src/index.js", PLACEHOLDER, "utf-8");
558
+
559
+ await runWrangler("init");
560
+ expect(fs.readFileSync("./src/index.js", "utf-8")).toBe(PLACEHOLDER);
561
+ expect(fs.existsSync("./src/index.ts")).toBe(false);
562
+ });
563
+
564
+ it("should not offer to create a worker in a ts project if a file already exists at the location", async () => {
565
+ mockConfirm(
566
+ {
567
+ text: "Would you like to install wrangler into your package.json?",
568
+ result: false,
569
+ },
570
+ {
571
+ text: "Would you like to use TypeScript?",
572
+ result: true,
573
+ }
574
+ );
575
+
576
+ fs.writeFileSync(
577
+ "./package.json",
578
+ JSON.stringify({ name: "test", version: "1.0.0" }),
579
+ "utf-8"
580
+ );
581
+ fs.mkdirSync("./src", { recursive: true });
582
+ const PLACEHOLDER = "/* placeholder text */";
583
+ fs.writeFileSync("./src/index.ts", PLACEHOLDER, "utf-8");
112
584
 
113
- await w("kv:namespace create UnitTestNamespace");
114
- expect(
115
- KVNamespaces.find((ns) => ns.title === `worker-UnitTestNamespace`)
116
- ).toBeTruthy();
585
+ await runWrangler("init");
586
+ expect(fs.existsSync("./src/index.js")).toBe(false);
587
+ expect(fs.readFileSync("./src/index.ts", "utf-8")).toBe(PLACEHOLDER);
117
588
  });
118
589
 
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;
590
+ it("should create a tsconfig.json and install `workers-types` if none is found and user confirms", async () => {
591
+ mockConfirm(
592
+ {
593
+ text: "No package.json found. Would you like to create one?",
594
+ result: true,
595
+ },
596
+ {
597
+ text: "Would you like to use TypeScript?",
598
+ result: true,
599
+ },
600
+ {
601
+ text: "Would you like to create a Worker at src/index.ts?",
602
+ result: false,
126
603
  }
127
604
  );
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"
605
+ await runWrangler("init");
606
+ expect(fs.existsSync("./tsconfig.json")).toBe(true);
607
+ const tsconfigJson = JSON.parse(
608
+ fs.readFileSync("./tsconfig.json", "utf-8")
132
609
  );
133
- expect(createdNamespace.title).toBe("worker-UnitTestNamespace");
610
+ expect(tsconfigJson.compilerOptions.types).toEqual([
611
+ "@cloudflare/workers-types",
612
+ ]);
613
+ expect(mockPackageManager.addDevDeps).toHaveBeenCalledWith(
614
+ "@cloudflare/workers-types",
615
+ "typescript"
616
+ );
617
+ });
618
+
619
+ it("should not touch an existing tsconfig.json in the same directory", async () => {
620
+ fs.writeFileSync(
621
+ "./package.json",
622
+ JSON.stringify({
623
+ name: "test",
624
+ version: "1.0.0",
625
+ devDependencies: {
626
+ wrangler: "0.0.0",
627
+ "@cloudflare/workers-types": "0.0.0",
628
+ },
629
+ }),
630
+ "utf-8"
631
+ );
632
+ fs.writeFileSync(
633
+ "./tsconfig.json",
634
+ JSON.stringify({ compilerOptions: {} }),
635
+ "utf-8"
636
+ );
637
+
638
+ await runWrangler("init");
639
+ const tsconfigJson = JSON.parse(
640
+ fs.readFileSync("./tsconfig.json", "utf-8")
641
+ );
642
+ expect(tsconfigJson.compilerOptions).toEqual({});
134
643
  });
135
644
 
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
- );
645
+ it("should offer to install type definitions in an existing typescript project", async () => {
646
+ mockConfirm(
647
+ {
648
+ text: "Would you like to install wrangler into your package.json?",
649
+ result: false,
650
+ },
651
+ {
652
+ text: "Would you like to install the type definitions for Workers into your package.json?",
653
+ result: true,
654
+ },
655
+ {
656
+ text: "Would you like to create a Worker at src/index.ts?",
657
+ result: false,
145
658
  }
146
659
  );
147
- await w(`kv:namespace delete --namespace-id ${namespaceIdToDelete}`);
148
- expect(KVNamespaces.find((ns) => ns.id === namespaceIdToDelete)).toBe(
149
- undefined
660
+ fs.writeFileSync(
661
+ "./package.json",
662
+ JSON.stringify({
663
+ name: "test",
664
+ version: "1.0.0",
665
+ }),
666
+ "utf-8"
667
+ );
668
+ fs.writeFileSync(
669
+ "./tsconfig.json",
670
+ JSON.stringify({ compilerOptions: {} }),
671
+ "utf-8"
672
+ );
673
+
674
+ await runWrangler("init");
675
+ const tsconfigJson = JSON.parse(
676
+ fs.readFileSync("./tsconfig.json", "utf-8")
677
+ );
678
+ // unchanged tsconfig
679
+ expect(tsconfigJson.compilerOptions).toEqual({});
680
+ expect(mockPackageManager.addDevDeps).toHaveBeenCalledWith(
681
+ "@cloudflare/workers-types"
682
+ );
683
+ });
684
+
685
+ it("should not touch an existing tsconfig.json in an ancestor directory", async () => {
686
+ fs.writeFileSync(
687
+ "./package.json",
688
+ JSON.stringify({
689
+ name: "test",
690
+ version: "1.0.0",
691
+ devDependencies: {
692
+ wrangler: "0.0.0",
693
+ "@cloudflare/workers-types": "0.0.0",
694
+ },
695
+ }),
696
+ "utf-8"
697
+ );
698
+ fs.writeFileSync(
699
+ "./tsconfig.json",
700
+ JSON.stringify({ compilerOptions: {} }),
701
+ "utf-8"
702
+ );
703
+
704
+ fs.mkdirSync("./sub-1/sub-2", { recursive: true });
705
+ process.chdir("./sub-1/sub-2");
706
+
707
+ await runWrangler("init");
708
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
709
+ expect(fs.existsSync("../../tsconfig.json")).toBe(true);
710
+
711
+ const tsconfigJson = JSON.parse(
712
+ fs.readFileSync("../../tsconfig.json", "utf-8")
713
+ );
714
+ expect(tsconfigJson.compilerOptions).toEqual({});
715
+ });
716
+
717
+ it("should error if `--type` is used", async () => {
718
+ await expect(
719
+ runWrangler("init --type")
720
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
721
+ `"The --type option is no longer supported."`
722
+ );
723
+ });
724
+
725
+ it("should error if `--type javascript` is used", async () => {
726
+ await expect(
727
+ runWrangler("init --type javascript")
728
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
729
+ `"The --type option is no longer supported."`
150
730
  );
151
731
  });
732
+
733
+ it("should error if `--type rust` is used", async () => {
734
+ await expect(
735
+ runWrangler("init --type rust")
736
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
737
+ `"The --type option is no longer supported."`
738
+ );
739
+ });
740
+
741
+ it("should error if `--type webpack` is used", async () => {
742
+ await expect(runWrangler("init --type webpack")).rejects
743
+ .toThrowErrorMatchingInlineSnapshot(`
744
+ "The --type option is no longer supported.
745
+ If you wish to use webpack then you will need to create a custom build."
746
+ `);
747
+ });
152
748
  });
153
749
  });