wrangler 0.0.0-e61907d → 0.0.0-e95bea2

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 (93) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +36 -2
  3. package/import_meta_url.js +3 -0
  4. package/package.json +79 -21
  5. package/pages/functions/buildWorker.ts +62 -0
  6. package/pages/functions/filepath-routing.test.ts +123 -0
  7. package/pages/functions/filepath-routing.ts +178 -0
  8. package/pages/functions/identifiers.ts +78 -0
  9. package/pages/functions/routes.ts +151 -0
  10. package/pages/functions/template-worker.ts +130 -0
  11. package/src/__tests__/configuration.test.ts +2217 -0
  12. package/src/__tests__/dev.test.tsx +405 -0
  13. package/src/__tests__/dev2.test.tsx +152 -0
  14. package/src/__tests__/guess-worker-format.test.ts +58 -0
  15. package/src/__tests__/helpers/clipboardy-mock.js +4 -0
  16. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  17. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  18. package/src/__tests__/helpers/mock-account-id.ts +44 -0
  19. package/src/__tests__/helpers/mock-bin.ts +36 -0
  20. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  21. package/src/__tests__/helpers/mock-console.ts +70 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  23. package/src/__tests__/helpers/mock-kv.ts +40 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  25. package/src/__tests__/helpers/mock-user.ts +27 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +127 -0
  31. package/src/__tests__/index.test.ts +991 -0
  32. package/src/__tests__/jest.setup.ts +69 -0
  33. package/src/__tests__/kv.test.ts +1408 -0
  34. package/src/__tests__/logout.test.ts +50 -0
  35. package/src/__tests__/package-manager.test.ts +206 -0
  36. package/src/__tests__/pages.test.ts +44 -0
  37. package/src/__tests__/parse.test.ts +322 -0
  38. package/src/__tests__/publish.test.ts +2453 -0
  39. package/src/__tests__/r2.test.ts +198 -0
  40. package/src/__tests__/route.test.ts +45 -0
  41. package/src/__tests__/secret.test.ts +425 -0
  42. package/src/__tests__/sentry.test.ts +146 -0
  43. package/src/__tests__/tail.test.ts +564 -0
  44. package/src/__tests__/whoami.test.tsx +86 -0
  45. package/src/bundle.ts +142 -0
  46. package/src/cfetch/index.ts +104 -0
  47. package/src/cfetch/internal.ts +135 -0
  48. package/src/cli.ts +19 -0
  49. package/src/config/README.md +107 -0
  50. package/src/config/config.ts +279 -0
  51. package/src/config/diagnostics.ts +80 -0
  52. package/src/config/environment.ts +305 -0
  53. package/src/config/index.ts +52 -0
  54. package/src/config/validation-helpers.ts +388 -0
  55. package/src/config/validation.ts +1027 -0
  56. package/src/create-worker-preview.ts +166 -0
  57. package/src/create-worker-upload-form.ts +217 -0
  58. package/src/dev/dev.tsx +357 -0
  59. package/src/dev/local.tsx +241 -0
  60. package/src/dev/remote.tsx +201 -0
  61. package/src/dev/use-esbuild.ts +100 -0
  62. package/src/dialogs.tsx +77 -0
  63. package/src/entry.ts +159 -0
  64. package/src/environment-variables.ts +33 -0
  65. package/src/https-options.ts +122 -0
  66. package/src/index.tsx +2329 -0
  67. package/src/inspect.ts +617 -0
  68. package/src/kv/index.tsx +339 -0
  69. package/src/module-collection.ts +253 -0
  70. package/src/open-in-browser.ts +25 -0
  71. package/src/package-manager.ts +126 -0
  72. package/src/pages.tsx +1045 -0
  73. package/src/parse.ts +183 -0
  74. package/src/paths.ts +26 -0
  75. package/src/proxy.ts +438 -0
  76. package/src/publish.ts +354 -0
  77. package/src/r2.ts +50 -0
  78. package/src/reporting.ts +131 -0
  79. package/src/selfsigned.d.ts +29 -0
  80. package/src/sites.tsx +238 -0
  81. package/src/tail/filters.ts +279 -0
  82. package/src/tail/index.ts +299 -0
  83. package/src/tail/printing.ts +62 -0
  84. package/src/user.tsx +1065 -0
  85. package/src/whoami.tsx +69 -0
  86. package/src/worker.ts +163 -0
  87. package/templates/new-worker.js +15 -0
  88. package/templates/new-worker.ts +15 -0
  89. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  90. package/templates/tsconfig.json +105 -0
  91. package/wrangler-dist/{index_node.js → cli.js} +105532 -67432
  92. package/wrangler-dist/cli.js.map +7 -0
  93. package/wrangler-dist/index_node.js.map +0 -7
@@ -0,0 +1,1408 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { Headers } from "undici";
3
+ import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
4
+ import {
5
+ setMockResponse,
6
+ unsetAllMocks,
7
+ unsetMockFetchKVGetValues,
8
+ setMockFetchKVGetValue,
9
+ } from "./helpers/mock-cfetch";
10
+ import { mockConsoleMethods } from "./helpers/mock-console";
11
+ import { mockConfirm } from "./helpers/mock-dialogs";
12
+ import { mockKeyListRequest } from "./helpers/mock-kv";
13
+ import { runInTempDir } from "./helpers/run-in-tmp";
14
+ import { runWrangler } from "./helpers/run-wrangler";
15
+ import type { KeyValue, KVNamespaceInfo, NamespaceKeyInfo } from "../kv";
16
+
17
+ describe("wrangler", () => {
18
+ mockAccountId();
19
+ mockApiToken();
20
+ runInTempDir();
21
+ const std = mockConsoleMethods();
22
+
23
+ afterEach(() => {
24
+ unsetAllMocks();
25
+ });
26
+
27
+ describe("kv:namespace", () => {
28
+ describe("create", () => {
29
+ function mockCreateRequest(expectedTitle: string) {
30
+ setMockResponse(
31
+ "/accounts/:accountId/storage/kv/namespaces",
32
+ "POST",
33
+ ([_url, accountId], { body }) => {
34
+ expect(accountId).toEqual("some-account-id");
35
+ const title = JSON.parse(body as string).title;
36
+ expect(title).toEqual(expectedTitle);
37
+ return { id: "some-namespace-id" };
38
+ }
39
+ );
40
+ }
41
+
42
+ it("should error if no namespace is given", async () => {
43
+ await expect(
44
+ runWrangler("kv:namespace create")
45
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
46
+ `"Not enough non-option arguments: got 0, need at least 1"`
47
+ );
48
+ expect(std.out).toMatchInlineSnapshot(`""`);
49
+ expect(std.err).toMatchInlineSnapshot(`
50
+ "wrangler kv:namespace create <namespace>
51
+
52
+ Create a new namespace
53
+
54
+ Positionals:
55
+ namespace The name of the new namespace [string] [required]
56
+
57
+ Flags:
58
+ -c, --config Path to .toml configuration file [string]
59
+ -h, --help Show help [boolean]
60
+ -v, --version Show version number [boolean]
61
+ --legacy-env Use legacy environments [boolean]
62
+
63
+ Options:
64
+ --env Perform on a specific environment [string]
65
+ --preview Interact with a preview namespace [boolean]
66
+
67
+ Not enough non-option arguments: got 0, need at least 1"
68
+ `);
69
+ });
70
+
71
+ it("should error if the namespace to create contains spaces", async () => {
72
+ await expect(
73
+ runWrangler("kv:namespace create abc def ghi")
74
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
75
+ `"Unexpected additional positional arguments \\"def ghi\\"."`
76
+ );
77
+ expect(std.out).toMatchInlineSnapshot(`""`);
78
+ expect(std.err).toMatchInlineSnapshot(`
79
+ "wrangler kv:namespace create <namespace>
80
+
81
+ Create a new namespace
82
+
83
+ Positionals:
84
+ namespace The name of the new namespace [string] [required]
85
+
86
+ Flags:
87
+ -c, --config Path to .toml configuration file [string]
88
+ -h, --help Show help [boolean]
89
+ -v, --version Show version number [boolean]
90
+ --legacy-env Use legacy environments [boolean]
91
+
92
+ Options:
93
+ --env Perform on a specific environment [string]
94
+ --preview Interact with a preview namespace [boolean]
95
+
96
+ Unexpected additional positional arguments \\"def ghi\\"."
97
+ `);
98
+ });
99
+
100
+ it("should error if the namespace to create is not valid", async () => {
101
+ await expect(
102
+ runWrangler("kv:namespace create abc-def")
103
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
104
+ `"The namespace binding name \\"abc-def\\" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number."`
105
+ );
106
+
107
+ expect(std.out).toMatchInlineSnapshot(`""`);
108
+ expect(std.err).toMatchInlineSnapshot(`
109
+ "wrangler kv:namespace create <namespace>
110
+
111
+ Create a new namespace
112
+
113
+ Positionals:
114
+ namespace The name of the new namespace [string] [required]
115
+
116
+ Flags:
117
+ -c, --config Path to .toml configuration file [string]
118
+ -h, --help Show help [boolean]
119
+ -v, --version Show version number [boolean]
120
+ --legacy-env Use legacy environments [boolean]
121
+
122
+ Options:
123
+ --env Perform on a specific environment [string]
124
+ --preview Interact with a preview namespace [boolean]
125
+
126
+ The namespace binding name \\"abc-def\\" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number."
127
+ `);
128
+ });
129
+
130
+ it("should create a namespace", async () => {
131
+ mockCreateRequest("worker-UnitTestNamespace");
132
+ await runWrangler("kv:namespace create UnitTestNamespace");
133
+ expect(std.out).toMatchInlineSnapshot(`
134
+ "🌀 Creating namespace with title \\"worker-UnitTestNamespace\\"
135
+ ✨ Success!
136
+ Add the following to your configuration file in your kv_namespaces array:
137
+ { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
138
+ `);
139
+ });
140
+
141
+ it("should create a preview namespace if configured to do so", async () => {
142
+ mockCreateRequest("worker-UnitTestNamespace_preview");
143
+ await runWrangler("kv:namespace create UnitTestNamespace --preview");
144
+ expect(std.out).toMatchInlineSnapshot(`
145
+ "🌀 Creating namespace with title \\"worker-UnitTestNamespace_preview\\"
146
+ ✨ Success!
147
+ Add the following to your configuration file in your kv_namespaces array:
148
+ { binding = \\"UnitTestNamespace\\", preview_id = \\"some-namespace-id\\" }"
149
+ `);
150
+ });
151
+
152
+ it("should create a namespace using configured worker name", async () => {
153
+ writeFileSync("./wrangler.toml", 'name = "otherWorker"', "utf-8");
154
+ mockCreateRequest("otherWorker-UnitTestNamespace");
155
+ await runWrangler("kv:namespace create UnitTestNamespace");
156
+ expect(std.out).toMatchInlineSnapshot(`
157
+ "🌀 Creating namespace with title \\"otherWorker-UnitTestNamespace\\"
158
+ ✨ Success!
159
+ Add the following to your configuration file in your kv_namespaces array:
160
+ { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
161
+ `);
162
+ });
163
+
164
+ it("should create a namespace in an environment if configured to do so", async () => {
165
+ mockCreateRequest("worker-customEnv-UnitTestNamespace");
166
+ await runWrangler(
167
+ "kv:namespace create UnitTestNamespace --env customEnv"
168
+ );
169
+ expect(std.out).toMatchInlineSnapshot(`
170
+ "🌀 Creating namespace with title \\"worker-customEnv-UnitTestNamespace\\"
171
+ ✨ Success!
172
+ Add the following to your configuration file in your kv_namespaces array under [env.customEnv]:
173
+ { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
174
+ `);
175
+ });
176
+ });
177
+
178
+ describe("list", () => {
179
+ function mockListRequest(namespaces: unknown[]) {
180
+ const requests = { count: 0 };
181
+ setMockResponse(
182
+ "/accounts/:accountId/storage/kv/namespaces",
183
+ ([_url, accountId], init, query) => {
184
+ requests.count++;
185
+ expect(accountId).toEqual("some-account-id");
186
+ expect(query.get("per_page")).toEqual("100");
187
+ expect(query.get("order")).toEqual("title");
188
+ expect(query.get("direction")).toEqual("asc");
189
+ expect(query.get("page")).toEqual(`${requests.count}`);
190
+ expect(init).toEqual({});
191
+ const pageSize = Number(query.get("per_page"));
192
+ const page = Number(query.get("page"));
193
+ return namespaces.slice((page - 1) * pageSize, page * pageSize);
194
+ }
195
+ );
196
+ return requests;
197
+ }
198
+
199
+ it("should list namespaces", async () => {
200
+ const kvNamespaces: KVNamespaceInfo[] = [
201
+ { title: "title-1", id: "id-1" },
202
+ { title: "title-2", id: "id-2" },
203
+ ];
204
+ mockListRequest(kvNamespaces);
205
+ await runWrangler("kv:namespace list");
206
+
207
+ expect(std.err).toMatchInlineSnapshot(`""`);
208
+ const namespaces = JSON.parse(std.out);
209
+ expect(namespaces).toEqual(kvNamespaces);
210
+ });
211
+
212
+ it("should make multiple requests for paginated results", async () => {
213
+ // Create a lot of mock namespaces, so that the fetch requests will be paginated
214
+ const kvNamespaces: KVNamespaceInfo[] = [];
215
+ for (let i = 0; i < 550; i++) {
216
+ kvNamespaces.push({ title: "title-" + i, id: "id-" + i });
217
+ }
218
+ const requests = mockListRequest(kvNamespaces);
219
+ await runWrangler("kv:namespace list");
220
+ const namespaces = JSON.parse(std.out);
221
+ expect(namespaces).toEqual(kvNamespaces);
222
+ expect(requests.count).toEqual(6);
223
+ });
224
+ });
225
+
226
+ describe("delete", () => {
227
+ function mockDeleteRequest(expectedNamespaceId: string) {
228
+ const requests = { count: 0 };
229
+ setMockResponse(
230
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId",
231
+ "DELETE",
232
+ ([_url, accountId, namespaceId]) => {
233
+ requests.count++;
234
+ expect(accountId).toEqual("some-account-id");
235
+ expect(namespaceId).toEqual(expectedNamespaceId);
236
+ return null;
237
+ }
238
+ );
239
+ return requests;
240
+ }
241
+
242
+ it("should delete a namespace specified by id", async () => {
243
+ const requests = mockDeleteRequest("some-namespace-id");
244
+ await runWrangler(
245
+ `kv:namespace delete --namespace-id some-namespace-id`
246
+ );
247
+ expect(requests.count).toEqual(1);
248
+ });
249
+
250
+ it("should delete a namespace specified by binding name", async () => {
251
+ writeWranglerConfig();
252
+ const requests = mockDeleteRequest("bound-id");
253
+ await runWrangler(
254
+ `kv:namespace delete --binding someBinding --preview false`
255
+ );
256
+ expect(requests.count).toEqual(1);
257
+ });
258
+
259
+ it("should delete a preview namespace specified by binding name", async () => {
260
+ writeWranglerConfig();
261
+ const requests = mockDeleteRequest("preview-bound-id");
262
+ await runWrangler(
263
+ `kv:namespace delete --binding someBinding --preview`
264
+ );
265
+ expect(requests.count).toEqual(1);
266
+ });
267
+
268
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
269
+ writeWranglerConfig();
270
+ await expect(runWrangler("kv:namespace delete --binding otherBinding"))
271
+ .rejects.toThrowErrorMatchingInlineSnapshot(`
272
+ "Not able to delete namespace.
273
+ A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."
274
+ `);
275
+ expect(std.err).toMatchInlineSnapshot(`
276
+ "wrangler kv:namespace delete
277
+
278
+ Deletes a given namespace.
279
+
280
+ Flags:
281
+ -c, --config Path to .toml configuration file [string]
282
+ -h, --help Show help [boolean]
283
+ -v, --version Show version number [boolean]
284
+ --legacy-env Use legacy environments [boolean]
285
+
286
+ Options:
287
+ --binding The name of the namespace to delete [string]
288
+ --namespace-id The id of the namespace to delete [string]
289
+ --env Perform on a specific environment [string]
290
+ --preview Interact with a preview namespace [boolean]
291
+
292
+ Not able to delete namespace.
293
+ A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."
294
+ `);
295
+ });
296
+
297
+ it("should delete a namespace specified by binding name in a given environment", async () => {
298
+ writeWranglerConfig();
299
+ const requests = mockDeleteRequest("env-bound-id");
300
+ await runWrangler(
301
+ "kv:namespace delete --binding someBinding --env some-environment --preview false"
302
+ );
303
+
304
+ expect(std.out).toMatchInlineSnapshot(`""`);
305
+ expect(std.err).toMatchInlineSnapshot(`""`);
306
+ expect(requests.count).toEqual(1);
307
+ });
308
+
309
+ it("should delete a preview namespace specified by binding name in a given environment", async () => {
310
+ writeWranglerConfig();
311
+ const requests = mockDeleteRequest("preview-env-bound-id");
312
+ await runWrangler(
313
+ `kv:namespace delete --binding someBinding --env some-environment --preview`
314
+ );
315
+ expect(requests.count).toEqual(1);
316
+ });
317
+ });
318
+ });
319
+
320
+ describe("kv:key", () => {
321
+ describe("put", () => {
322
+ function mockKeyPutRequest(
323
+ expectedNamespaceId: string,
324
+ expectedKV: KeyValue
325
+ ) {
326
+ const requests = { count: 0 };
327
+ setMockResponse(
328
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key",
329
+ "PUT",
330
+ ([_url, accountId, namespaceId, key], { body }, query) => {
331
+ requests.count++;
332
+ expect(accountId).toEqual("some-account-id");
333
+ expect(namespaceId).toEqual(expectedNamespaceId);
334
+ expect(key).toEqual(expectedKV.key);
335
+ expect(body).toEqual(expectedKV.value);
336
+ if (expectedKV.expiration !== undefined) {
337
+ expect(query.get("expiration")).toEqual(
338
+ `${expectedKV.expiration}`
339
+ );
340
+ } else {
341
+ expect(query.has("expiration")).toBe(false);
342
+ }
343
+ if (expectedKV.expiration_ttl) {
344
+ expect(query.get("expiration_ttl")).toEqual(
345
+ `${expectedKV.expiration_ttl}`
346
+ );
347
+ } else {
348
+ expect(query.has("expiration_ttl")).toBe(false);
349
+ }
350
+ return null;
351
+ }
352
+ );
353
+ return requests;
354
+ }
355
+
356
+ it("should put a key in a given namespace specified by namespace-id", async () => {
357
+ const requests = mockKeyPutRequest("some-namespace-id", {
358
+ key: "my-key",
359
+ value: "my-value",
360
+ });
361
+
362
+ await runWrangler(
363
+ "kv:key put my-key my-value --namespace-id some-namespace-id"
364
+ );
365
+
366
+ expect(requests.count).toEqual(1);
367
+ expect(std.out).toMatchInlineSnapshot(
368
+ `"writing the value \\"my-value\\" to key \\"my-key\\" on namespace some-namespace-id"`
369
+ );
370
+ expect(std.err).toMatchInlineSnapshot(`""`);
371
+ });
372
+
373
+ it("should put a key in a given namespace specified by binding", async () => {
374
+ writeWranglerConfig();
375
+ const requests = mockKeyPutRequest("bound-id", {
376
+ key: "my-key",
377
+ value: "my-value",
378
+ });
379
+ await runWrangler(
380
+ "kv:key put my-key my-value --binding someBinding --preview false"
381
+ );
382
+
383
+ expect(std.out).toMatchInlineSnapshot(
384
+ `"writing the value \\"my-value\\" to key \\"my-key\\" on namespace bound-id"`
385
+ );
386
+ expect(std.err).toMatchInlineSnapshot(`""`);
387
+ expect(requests.count).toEqual(1);
388
+ });
389
+
390
+ it("should put a key in a given preview namespace specified by binding", async () => {
391
+ writeWranglerConfig();
392
+ const requests = mockKeyPutRequest("preview-bound-id", {
393
+ key: "my-key",
394
+ value: "my-value",
395
+ });
396
+
397
+ await runWrangler(
398
+ "kv:key put my-key my-value --binding someBinding --preview"
399
+ );
400
+
401
+ expect(std.out).toMatchInlineSnapshot(
402
+ `"writing the value \\"my-value\\" to key \\"my-key\\" on namespace preview-bound-id"`
403
+ );
404
+ expect(std.err).toMatchInlineSnapshot(`""`);
405
+ expect(requests.count).toEqual(1);
406
+ });
407
+
408
+ it("should add expiration and ttl properties when putting a key", async () => {
409
+ const requests = mockKeyPutRequest("some-namespace-id", {
410
+ key: "my-key",
411
+ value: "my-value",
412
+ expiration: 10,
413
+ expiration_ttl: 20,
414
+ });
415
+ await runWrangler(
416
+ "kv:key put my-key my-value --namespace-id some-namespace-id --expiration 10 --ttl 20"
417
+ );
418
+ expect(requests.count).toEqual(1);
419
+ expect(std.out).toMatchInlineSnapshot(
420
+ `"writing the value \\"my-value\\" to key \\"my-key\\" on namespace some-namespace-id"`
421
+ );
422
+ expect(std.err).toMatchInlineSnapshot(`""`);
423
+ });
424
+
425
+ it("should put a key to the specified environment in a given namespace", async () => {
426
+ writeWranglerConfig();
427
+ const requests = mockKeyPutRequest("env-bound-id", {
428
+ key: "my-key",
429
+ value: "my-value",
430
+ });
431
+ await runWrangler(
432
+ "kv:key put my-key my-value --binding someBinding --env some-environment --preview false"
433
+ );
434
+ expect(std.out).toMatchInlineSnapshot(
435
+ `"writing the value \\"my-value\\" to key \\"my-key\\" on namespace env-bound-id"`
436
+ );
437
+ expect(std.err).toMatchInlineSnapshot(`""`);
438
+ expect(requests.count).toEqual(1);
439
+ });
440
+
441
+ it("should put a key with a value loaded from a given path", async () => {
442
+ writeFileSync("foo.txt", "file-contents", "utf-8");
443
+ const requests = mockKeyPutRequest("some-namespace-id", {
444
+ key: "my-key",
445
+ value: "file-contents",
446
+ });
447
+ await runWrangler(
448
+ "kv:key put my-key --namespace-id some-namespace-id --path foo.txt"
449
+ );
450
+ expect(std.out).toMatchInlineSnapshot(
451
+ `"writing the contents of foo.txt to the key \\"my-key\\" on namespace some-namespace-id"`
452
+ );
453
+ expect(std.err).toMatchInlineSnapshot(`""`);
454
+ expect(requests.count).toEqual(1);
455
+ });
456
+
457
+ it("should error if no key is provided", async () => {
458
+ await expect(
459
+ runWrangler("kv:key put")
460
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
461
+ `"Not enough non-option arguments: got 0, need at least 1"`
462
+ );
463
+
464
+ expect(std.out).toMatchInlineSnapshot(`""`);
465
+ expect(std.err).toMatchInlineSnapshot(`
466
+ "wrangler kv:key put <key> [value]
467
+
468
+ Writes a single key/value pair to the given namespace.
469
+
470
+ Positionals:
471
+ key The key to write to [string] [required]
472
+ value The value to write [string]
473
+
474
+ Flags:
475
+ -c, --config Path to .toml configuration file [string]
476
+ -h, --help Show help [boolean]
477
+ -v, --version Show version number [boolean]
478
+ --legacy-env Use legacy environments [boolean]
479
+
480
+ Options:
481
+ --binding The binding of the namespace to write to [string]
482
+ --namespace-id The id of the namespace to write to [string]
483
+ --env Perform on a specific environment [string]
484
+ --preview Interact with a preview namespace [boolean]
485
+ --ttl Time for which the entries should be visible [number]
486
+ --expiration Time since the UNIX epoch after which the entry expires [number]
487
+ --path Read value from the file at a given path [string]
488
+
489
+ Not enough non-option arguments: got 0, need at least 1"
490
+ `);
491
+ });
492
+
493
+ it("should error if no binding nor namespace is provided", async () => {
494
+ await expect(
495
+ runWrangler("kv:key put foo bar")
496
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
497
+ `"Exactly one of the arguments binding and namespace-id is required"`
498
+ );
499
+
500
+ expect(std.out).toMatchInlineSnapshot(`""`);
501
+ expect(std.err).toMatchInlineSnapshot(`
502
+ "wrangler kv:key put <key> [value]
503
+
504
+ Writes a single key/value pair to the given namespace.
505
+
506
+ Positionals:
507
+ key The key to write to [string] [required]
508
+ value The value to write [string]
509
+
510
+ Flags:
511
+ -c, --config Path to .toml configuration file [string]
512
+ -h, --help Show help [boolean]
513
+ -v, --version Show version number [boolean]
514
+ --legacy-env Use legacy environments [boolean]
515
+
516
+ Options:
517
+ --binding The binding of the namespace to write to [string]
518
+ --namespace-id The id of the namespace to write to [string]
519
+ --env Perform on a specific environment [string]
520
+ --preview Interact with a preview namespace [boolean]
521
+ --ttl Time for which the entries should be visible [number]
522
+ --expiration Time since the UNIX epoch after which the entry expires [number]
523
+ --path Read value from the file at a given path [string]
524
+
525
+ Exactly one of the arguments binding and namespace-id is required"
526
+ `);
527
+ });
528
+
529
+ it("should error if both binding and namespace is provided", async () => {
530
+ await expect(
531
+ runWrangler("kv:key put foo bar --binding x --namespace-id y")
532
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
533
+ `"Arguments binding and namespace-id are mutually exclusive"`
534
+ );
535
+
536
+ expect(std.out).toMatchInlineSnapshot(`""`);
537
+ expect(std.err).toMatchInlineSnapshot(`
538
+ "wrangler kv:key put <key> [value]
539
+
540
+ Writes a single key/value pair to the given namespace.
541
+
542
+ Positionals:
543
+ key The key to write to [string] [required]
544
+ value The value to write [string]
545
+
546
+ Flags:
547
+ -c, --config Path to .toml configuration file [string]
548
+ -h, --help Show help [boolean]
549
+ -v, --version Show version number [boolean]
550
+ --legacy-env Use legacy environments [boolean]
551
+
552
+ Options:
553
+ --binding The binding of the namespace to write to [string]
554
+ --namespace-id The id of the namespace to write to [string]
555
+ --env Perform on a specific environment [string]
556
+ --preview Interact with a preview namespace [boolean]
557
+ --ttl Time for which the entries should be visible [number]
558
+ --expiration Time since the UNIX epoch after which the entry expires [number]
559
+ --path Read value from the file at a given path [string]
560
+
561
+ Arguments binding and namespace-id are mutually exclusive"
562
+ `);
563
+ });
564
+
565
+ it("should error if no value nor path is provided", async () => {
566
+ await expect(
567
+ runWrangler("kv:key put key --namespace-id 12345")
568
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
569
+ `"Exactly one of the arguments value and path is required"`
570
+ );
571
+
572
+ expect(std.out).toMatchInlineSnapshot(`""`);
573
+ expect(std.err).toMatchInlineSnapshot(`
574
+ "wrangler kv:key put <key> [value]
575
+
576
+ Writes a single key/value pair to the given namespace.
577
+
578
+ Positionals:
579
+ key The key to write to [string] [required]
580
+ value The value to write [string]
581
+
582
+ Flags:
583
+ -c, --config Path to .toml configuration file [string]
584
+ -h, --help Show help [boolean]
585
+ -v, --version Show version number [boolean]
586
+ --legacy-env Use legacy environments [boolean]
587
+
588
+ Options:
589
+ --binding The binding of the namespace to write to [string]
590
+ --namespace-id The id of the namespace to write to [string]
591
+ --env Perform on a specific environment [string]
592
+ --preview Interact with a preview namespace [boolean]
593
+ --ttl Time for which the entries should be visible [number]
594
+ --expiration Time since the UNIX epoch after which the entry expires [number]
595
+ --path Read value from the file at a given path [string]
596
+
597
+ Exactly one of the arguments value and path is required"
598
+ `);
599
+ });
600
+
601
+ it("should error if both value and path is provided", async () => {
602
+ await expect(
603
+ runWrangler("kv:key put key value --path xyz --namespace-id 12345")
604
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
605
+ `"Arguments value and path are mutually exclusive"`
606
+ );
607
+
608
+ expect(std.out).toMatchInlineSnapshot(`""`);
609
+ expect(std.err).toMatchInlineSnapshot(`
610
+ "wrangler kv:key put <key> [value]
611
+
612
+ Writes a single key/value pair to the given namespace.
613
+
614
+ Positionals:
615
+ key The key to write to [string] [required]
616
+ value The value to write [string]
617
+
618
+ Flags:
619
+ -c, --config Path to .toml configuration file [string]
620
+ -h, --help Show help [boolean]
621
+ -v, --version Show version number [boolean]
622
+ --legacy-env Use legacy environments [boolean]
623
+
624
+ Options:
625
+ --binding The binding of the namespace to write to [string]
626
+ --namespace-id The id of the namespace to write to [string]
627
+ --env Perform on a specific environment [string]
628
+ --preview Interact with a preview namespace [boolean]
629
+ --ttl Time for which the entries should be visible [number]
630
+ --expiration Time since the UNIX epoch after which the entry expires [number]
631
+ --path Read value from the file at a given path [string]
632
+
633
+ Arguments value and path are mutually exclusive"
634
+ `);
635
+ });
636
+
637
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
638
+ writeWranglerConfig();
639
+ await expect(
640
+ runWrangler("kv:key put key value --binding otherBinding")
641
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
642
+ `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
643
+ );
644
+
645
+ expect(std.out).toMatchInlineSnapshot(`""`);
646
+ expect(std.err).toMatchInlineSnapshot(`
647
+ "A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
648
+
649
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
650
+ `);
651
+ });
652
+
653
+ it("should error if a given binding has both preview and non-preview and --preview is not specified", async () => {
654
+ writeWranglerConfig();
655
+ const requests = mockKeyPutRequest("preview-bound-id", {
656
+ key: "my-key",
657
+ value: "my-value",
658
+ });
659
+ await expect(
660
+ runWrangler("kv:key put my-key my-value --binding someBinding")
661
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
662
+ `"someBinding has both a namespace ID and a preview ID. Specify \\"--preview\\" or \\"--preview false\\" to avoid writing data to the wrong namespace."`
663
+ );
664
+ expect(std.out).toMatchInlineSnapshot(`""`);
665
+ expect(std.err).toMatchInlineSnapshot(`
666
+ "someBinding has both a namespace ID and a preview ID. Specify \\"--preview\\" or \\"--preview false\\" to avoid writing data to the wrong namespace.
667
+
668
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
669
+ `);
670
+ expect(requests.count).toEqual(0);
671
+ });
672
+ });
673
+
674
+ describe("list", () => {
675
+ it("should list the keys of a namespace specified by namespace-id", async () => {
676
+ const keys = ["key-1", "key-2", "key-3"];
677
+ mockKeyListRequest("some-namespace-id", keys);
678
+ await runWrangler("kv:key list --namespace-id some-namespace-id");
679
+ expect(std.err).toMatchInlineSnapshot(`""`);
680
+ expect(std.out).toMatchInlineSnapshot(`
681
+ "[
682
+ {
683
+ \\"name\\": \\"key-1\\",
684
+ \\"expiration\\": 123456789,
685
+ \\"metadata\\": {}
686
+ },
687
+ {
688
+ \\"name\\": \\"key-2\\",
689
+ \\"expiration\\": 123456789,
690
+ \\"metadata\\": {}
691
+ },
692
+ {
693
+ \\"name\\": \\"key-3\\",
694
+ \\"expiration\\": 123456789,
695
+ \\"metadata\\": {}
696
+ }
697
+ ]"
698
+ `);
699
+ });
700
+
701
+ it("should list the keys of a namespace specified by binding", async () => {
702
+ writeWranglerConfig();
703
+ const keys = ["key-1", "key-2", "key-3"];
704
+ mockKeyListRequest("bound-id", keys);
705
+
706
+ await runWrangler("kv:key list --binding someBinding");
707
+ expect(std.err).toMatchInlineSnapshot(`""`);
708
+ expect(std.out).toMatchInlineSnapshot(`
709
+ "[
710
+ {
711
+ \\"name\\": \\"key-1\\",
712
+ \\"expiration\\": 123456789,
713
+ \\"metadata\\": {}
714
+ },
715
+ {
716
+ \\"name\\": \\"key-2\\",
717
+ \\"expiration\\": 123456789,
718
+ \\"metadata\\": {}
719
+ },
720
+ {
721
+ \\"name\\": \\"key-3\\",
722
+ \\"expiration\\": 123456789,
723
+ \\"metadata\\": {}
724
+ }
725
+ ]"
726
+ `);
727
+ });
728
+
729
+ it("should list the keys of a preview namespace specified by binding", async () => {
730
+ writeWranglerConfig();
731
+ const keys = ["key-1", "key-2", "key-3"];
732
+ mockKeyListRequest("preview-bound-id", keys);
733
+ await runWrangler("kv:key list --binding someBinding --preview");
734
+ expect(std.err).toMatchInlineSnapshot(`""`);
735
+ expect(std.out).toMatchInlineSnapshot(`
736
+ "[
737
+ {
738
+ \\"name\\": \\"key-1\\",
739
+ \\"expiration\\": 123456789,
740
+ \\"metadata\\": {}
741
+ },
742
+ {
743
+ \\"name\\": \\"key-2\\",
744
+ \\"expiration\\": 123456789,
745
+ \\"metadata\\": {}
746
+ },
747
+ {
748
+ \\"name\\": \\"key-3\\",
749
+ \\"expiration\\": 123456789,
750
+ \\"metadata\\": {}
751
+ }
752
+ ]"
753
+ `);
754
+ });
755
+
756
+ it("should list the keys of a namespace specified by binding, in a given environment", async () => {
757
+ writeWranglerConfig();
758
+ const keys = ["key-1", "key-2", "key-3"];
759
+ mockKeyListRequest("env-bound-id", keys);
760
+ await runWrangler(
761
+ "kv:key list --binding someBinding --env some-environment"
762
+ );
763
+ expect(std.err).toMatchInlineSnapshot(`""`);
764
+ expect(std.out).toMatchInlineSnapshot(`
765
+ "[
766
+ {
767
+ \\"name\\": \\"key-1\\",
768
+ \\"expiration\\": 123456789,
769
+ \\"metadata\\": {}
770
+ },
771
+ {
772
+ \\"name\\": \\"key-2\\",
773
+ \\"expiration\\": 123456789,
774
+ \\"metadata\\": {}
775
+ },
776
+ {
777
+ \\"name\\": \\"key-3\\",
778
+ \\"expiration\\": 123456789,
779
+ \\"metadata\\": {}
780
+ }
781
+ ]"
782
+ `);
783
+ });
784
+
785
+ it("should list the keys of a preview namespace specified by binding, in a given environment", async () => {
786
+ writeWranglerConfig();
787
+ const keys = ["key-1", "key-2", "key-3"];
788
+ mockKeyListRequest("preview-env-bound-id", keys);
789
+ await runWrangler(
790
+ "kv:key list --binding someBinding --preview --env some-environment"
791
+ );
792
+ expect(std.err).toMatchInlineSnapshot(`""`);
793
+ expect(std.out).toMatchInlineSnapshot(`
794
+ "[
795
+ {
796
+ \\"name\\": \\"key-1\\",
797
+ \\"expiration\\": 123456789,
798
+ \\"metadata\\": {}
799
+ },
800
+ {
801
+ \\"name\\": \\"key-2\\",
802
+ \\"expiration\\": 123456789,
803
+ \\"metadata\\": {}
804
+ },
805
+ {
806
+ \\"name\\": \\"key-3\\",
807
+ \\"expiration\\": 123456789,
808
+ \\"metadata\\": {}
809
+ }
810
+ ]"
811
+ `);
812
+ });
813
+
814
+ // We'll run the next test with variations on the cursor
815
+ // that's returned on cloudflare's API after all results
816
+ // have been drained.
817
+ for (const blankCursorValue of [undefined, null, ""] as [
818
+ undefined,
819
+ null,
820
+ ""
821
+ ]) {
822
+ describe(`cursor - ${blankCursorValue}`, () => {
823
+ it("should make multiple requests for paginated results", async () => {
824
+ // Create a lot of mock keys, so that the fetch requests will be paginated
825
+ const keys: string[] = [];
826
+ for (let i = 0; i < 550; i++) {
827
+ keys.push("key-" + i);
828
+ }
829
+ // Ask for the keys in pages of size 100.
830
+ const requests = mockKeyListRequest(
831
+ "some-namespace-id",
832
+ keys,
833
+ 100,
834
+ blankCursorValue
835
+ );
836
+ await runWrangler(
837
+ "kv:key list --namespace-id some-namespace-id --limit 100"
838
+ );
839
+ expect(std.err).toMatchInlineSnapshot(`""`);
840
+ expect(
841
+ JSON.parse(std.out).map((k: NamespaceKeyInfo) => k.name)
842
+ ).toEqual(keys);
843
+ expect(requests.count).toEqual(6);
844
+ });
845
+ });
846
+ }
847
+
848
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
849
+ writeWranglerConfig();
850
+ await expect(
851
+ runWrangler("kv:key list --binding otherBinding")
852
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
853
+ `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
854
+ );
855
+ expect(std.err).toMatchInlineSnapshot(`
856
+ "A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
857
+
858
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
859
+ `);
860
+ expect(std.out).toMatchInlineSnapshot(`""`);
861
+ });
862
+ });
863
+
864
+ describe("get", () => {
865
+ afterEach(() => {
866
+ unsetMockFetchKVGetValues();
867
+ });
868
+
869
+ it("should get a key in a given namespace specified by namespace-id", async () => {
870
+ setMockFetchKVGetValue(
871
+ "some-account-id",
872
+ "some-namespace-id",
873
+ "my-key",
874
+ "my-value"
875
+ );
876
+ await runWrangler("kv:key get my-key --namespace-id some-namespace-id");
877
+ expect(std.out).toMatchInlineSnapshot(`"my-value"`);
878
+ expect(std.err).toMatchInlineSnapshot(`""`);
879
+ });
880
+
881
+ it("should get a key in a given namespace specified by binding", async () => {
882
+ writeWranglerConfig();
883
+ setMockFetchKVGetValue(
884
+ "some-account-id",
885
+ "bound-id",
886
+ "my-key",
887
+ "my-value"
888
+ );
889
+ await runWrangler(
890
+ "kv:key get my-key --binding someBinding --preview false"
891
+ );
892
+ expect(std.out).toMatchInlineSnapshot(`"my-value"`);
893
+ expect(std.err).toMatchInlineSnapshot(`""`);
894
+ });
895
+
896
+ it("should get a key in a given preview namespace specified by binding", async () => {
897
+ writeWranglerConfig();
898
+ setMockFetchKVGetValue(
899
+ "some-account-id",
900
+ "preview-bound-id",
901
+ "my-key",
902
+ "my-value"
903
+ );
904
+ await runWrangler("kv:key get my-key --binding someBinding --preview");
905
+ expect(std.out).toMatchInlineSnapshot(`"my-value"`);
906
+ expect(std.err).toMatchInlineSnapshot(`""`);
907
+ });
908
+
909
+ it("should get a key for the specified environment in a given namespace", async () => {
910
+ writeWranglerConfig();
911
+ setMockFetchKVGetValue(
912
+ "some-account-id",
913
+ "env-bound-id",
914
+ "my-key",
915
+ "my-value"
916
+ );
917
+ await runWrangler(
918
+ "kv:key get my-key my-value --binding someBinding --env some-environment --preview false"
919
+ );
920
+ expect(std.out).toMatchInlineSnapshot(`"my-value"`);
921
+ expect(std.err).toMatchInlineSnapshot(`""`);
922
+ });
923
+
924
+ it("should error if no key is provided", async () => {
925
+ await expect(
926
+ runWrangler("kv:key get")
927
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
928
+ `"Not enough non-option arguments: got 0, need at least 1"`
929
+ );
930
+ expect(std.out).toMatchInlineSnapshot(`""`);
931
+ expect(std.err).toMatchInlineSnapshot(`
932
+ "wrangler kv:key get <key>
933
+
934
+ Reads a single value by key from the given namespace.
935
+
936
+ Positionals:
937
+ key The key value to get. [string] [required]
938
+
939
+ Flags:
940
+ -c, --config Path to .toml configuration file [string]
941
+ -h, --help Show help [boolean]
942
+ -v, --version Show version number [boolean]
943
+ --legacy-env Use legacy environments [boolean]
944
+
945
+ Options:
946
+ --binding The name of the namespace to get from [string]
947
+ --namespace-id The id of the namespace to get from [string]
948
+ --env Perform on a specific environment [string]
949
+ --preview Interact with a preview namespace [boolean] [default: false]
950
+
951
+ Not enough non-option arguments: got 0, need at least 1"
952
+ `);
953
+ });
954
+
955
+ it("should error if no binding nor namespace is provided", async () => {
956
+ await expect(
957
+ runWrangler("kv:key get foo")
958
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
959
+ `"Exactly one of the arguments binding and namespace-id is required"`
960
+ );
961
+ expect(std.out).toMatchInlineSnapshot(`""`);
962
+ expect(std.err).toMatchInlineSnapshot(`
963
+ "wrangler kv:key get <key>
964
+
965
+ Reads a single value by key from the given namespace.
966
+
967
+ Positionals:
968
+ key The key value to get. [string] [required]
969
+
970
+ Flags:
971
+ -c, --config Path to .toml configuration file [string]
972
+ -h, --help Show help [boolean]
973
+ -v, --version Show version number [boolean]
974
+ --legacy-env Use legacy environments [boolean]
975
+
976
+ Options:
977
+ --binding The name of the namespace to get from [string]
978
+ --namespace-id The id of the namespace to get from [string]
979
+ --env Perform on a specific environment [string]
980
+ --preview Interact with a preview namespace [boolean] [default: false]
981
+
982
+ Exactly one of the arguments binding and namespace-id is required"
983
+ `);
984
+ });
985
+
986
+ it("should error if both binding and namespace is provided", async () => {
987
+ await expect(
988
+ runWrangler("kv:key get foo --binding x --namespace-id y")
989
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
990
+ `"Arguments binding and namespace-id are mutually exclusive"`
991
+ );
992
+
993
+ expect(std.out).toMatchInlineSnapshot(`""`);
994
+ expect(std.err).toMatchInlineSnapshot(`
995
+ "wrangler kv:key get <key>
996
+
997
+ Reads a single value by key from the given namespace.
998
+
999
+ Positionals:
1000
+ key The key value to get. [string] [required]
1001
+
1002
+ Flags:
1003
+ -c, --config Path to .toml configuration file [string]
1004
+ -h, --help Show help [boolean]
1005
+ -v, --version Show version number [boolean]
1006
+ --legacy-env Use legacy environments [boolean]
1007
+
1008
+ Options:
1009
+ --binding The name of the namespace to get from [string]
1010
+ --namespace-id The id of the namespace to get from [string]
1011
+ --env Perform on a specific environment [string]
1012
+ --preview Interact with a preview namespace [boolean] [default: false]
1013
+
1014
+ Arguments binding and namespace-id are mutually exclusive"
1015
+ `);
1016
+ });
1017
+
1018
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
1019
+ writeWranglerConfig();
1020
+ await expect(
1021
+ runWrangler("kv:key get key --binding otherBinding")
1022
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1023
+ `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
1024
+ );
1025
+ expect(std.out).toMatchInlineSnapshot(`""`);
1026
+ expect(std.err).toMatchInlineSnapshot(`
1027
+ "A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
1028
+
1029
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
1030
+ `);
1031
+ });
1032
+ });
1033
+
1034
+ describe("delete", () => {
1035
+ function mockDeleteRequest(
1036
+ expectedNamespaceId: string,
1037
+ expectedKey: string
1038
+ ) {
1039
+ const requests = { count: 0 };
1040
+ setMockResponse(
1041
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key",
1042
+ "DELETE",
1043
+ ([_url, accountId, namespaceId, key]) => {
1044
+ requests.count++;
1045
+ expect(accountId).toEqual("some-account-id");
1046
+ expect(namespaceId).toEqual(expectedNamespaceId);
1047
+ expect(key).toEqual(expectedKey);
1048
+ return null;
1049
+ }
1050
+ );
1051
+ return requests;
1052
+ }
1053
+
1054
+ it("should delete a key in a namespace specified by id", async () => {
1055
+ const requests = mockDeleteRequest("some-namespace-id", "someKey");
1056
+ await runWrangler(
1057
+ `kv:key delete --namespace-id some-namespace-id someKey`
1058
+ );
1059
+ expect(requests.count).toEqual(1);
1060
+ });
1061
+
1062
+ it("should delete a key in a namespace specified by binding name", async () => {
1063
+ writeWranglerConfig();
1064
+ const requests = mockDeleteRequest("bound-id", "someKey");
1065
+ await runWrangler(
1066
+ `kv:key delete --binding someBinding --preview false someKey`
1067
+ );
1068
+ expect(requests.count).toEqual(1);
1069
+ });
1070
+
1071
+ it("should delete a key in a preview namespace specified by binding name", async () => {
1072
+ writeWranglerConfig();
1073
+ const requests = mockDeleteRequest("preview-bound-id", "someKey");
1074
+ await runWrangler(
1075
+ `kv:key delete --binding someBinding --preview someKey`
1076
+ );
1077
+ expect(requests.count).toEqual(1);
1078
+ });
1079
+
1080
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
1081
+ writeWranglerConfig();
1082
+ await expect(
1083
+ runWrangler(`kv:key delete --binding otherBinding someKey`)
1084
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1085
+ `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
1086
+ );
1087
+
1088
+ expect(std.err).toMatchInlineSnapshot(`
1089
+ "A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
1090
+
1091
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
1092
+ `);
1093
+ });
1094
+
1095
+ it("should delete a key in a namespace specified by binding name in a given environment", async () => {
1096
+ writeWranglerConfig();
1097
+ const requests = mockDeleteRequest("env-bound-id", "someKey");
1098
+ await runWrangler(
1099
+ `kv:key delete --binding someBinding --env some-environment --preview false someKey`
1100
+ );
1101
+ expect(std.out).toMatchInlineSnapshot(
1102
+ `"deleting the key \\"someKey\\" on namespace env-bound-id"`
1103
+ );
1104
+ expect(std.err).toMatchInlineSnapshot(`""`);
1105
+ expect(requests.count).toEqual(1);
1106
+ });
1107
+
1108
+ it("should delete a key in a preview namespace specified by binding name in a given environment", async () => {
1109
+ writeWranglerConfig();
1110
+ const requests = mockDeleteRequest("preview-env-bound-id", "someKey");
1111
+ await runWrangler(
1112
+ `kv:key delete --binding someBinding --env some-environment --preview someKey`
1113
+ );
1114
+ expect(requests.count).toEqual(1);
1115
+ });
1116
+ });
1117
+ });
1118
+
1119
+ describe("kv:bulk", () => {
1120
+ describe("put", () => {
1121
+ function mockPutRequest(
1122
+ expectedNamespaceId: string,
1123
+ expectedKeyValues: KeyValue[]
1124
+ ) {
1125
+ const requests = { count: 0 };
1126
+ setMockResponse(
1127
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId/bulk",
1128
+ "PUT",
1129
+ ([_url, accountId, namespaceId], { body }) => {
1130
+ requests.count++;
1131
+ expect(accountId).toEqual("some-account-id");
1132
+ expect(namespaceId).toEqual(expectedNamespaceId);
1133
+ expect(JSON.parse(body as string)).toEqual(
1134
+ expectedKeyValues.slice(
1135
+ (requests.count - 1) * 5000,
1136
+ requests.count * 5000
1137
+ )
1138
+ );
1139
+ return null;
1140
+ }
1141
+ );
1142
+ return requests;
1143
+ }
1144
+
1145
+ it("should put the key-values parsed from a file", async () => {
1146
+ const keyValues: KeyValue[] = [
1147
+ { key: "someKey1", value: "someValue1" },
1148
+ { key: "ns:someKey2", value: "123", base64: true },
1149
+ { key: "someKey3", value: "someValue3", expiration: 100 },
1150
+ { key: "someKey4", value: "someValue4", expiration_ttl: 500 },
1151
+ ];
1152
+ writeFileSync("./keys.json", JSON.stringify(keyValues));
1153
+ const requests = mockPutRequest("some-namespace-id", keyValues);
1154
+ await runWrangler(
1155
+ `kv:bulk put --namespace-id some-namespace-id keys.json`
1156
+ );
1157
+ expect(requests.count).toEqual(1);
1158
+ expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1159
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1160
+ expect(std.err).toMatchInlineSnapshot(`""`);
1161
+ });
1162
+
1163
+ it("should put the key-values in batches of 5000 parsed from a file", async () => {
1164
+ const keyValues: KeyValue[] = new Array(12000).fill({
1165
+ key: "someKey1",
1166
+ value: "someValue1",
1167
+ });
1168
+ writeFileSync("./keys.json", JSON.stringify(keyValues));
1169
+ const requests = mockPutRequest("some-namespace-id", keyValues);
1170
+ await runWrangler(
1171
+ `kv:bulk put --namespace-id some-namespace-id keys.json`
1172
+ );
1173
+ expect(requests.count).toEqual(3);
1174
+ expect(std.out).toMatchInlineSnapshot(`
1175
+ "Uploaded 0 of 12000.
1176
+ Uploaded 5000 of 12000.
1177
+ Uploaded 10000 of 12000.
1178
+ Uploaded 12000 of 12000.
1179
+ Success!"
1180
+ `);
1181
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1182
+ expect(std.err).toMatchInlineSnapshot(`""`);
1183
+ });
1184
+
1185
+ it("should error if the file is not a JSON array", async () => {
1186
+ const keyValues = { key: "someKey1", value: "someValue1" };
1187
+ writeFileSync("./keys.json", JSON.stringify(keyValues));
1188
+ await expect(
1189
+ runWrangler(`kv:bulk put --namespace-id some-namespace-id keys.json`)
1190
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`
1191
+ "Unexpected JSON input from \\"keys.json\\".
1192
+ Expected an array of key-value objects but got type \\"object\\"."
1193
+ `);
1194
+ expect(std.out).toMatchInlineSnapshot(`""`);
1195
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1196
+ });
1197
+
1198
+ it("should error if the array contains items that are not key-value objects", async () => {
1199
+ const keyValues = [
1200
+ 123,
1201
+ "a string",
1202
+ { key: "someKey" },
1203
+ { value: "someValue" },
1204
+ { key: "someKey1", value: "someValue1", invalid: true },
1205
+ ];
1206
+ writeFileSync("./keys.json", JSON.stringify(keyValues));
1207
+ await expect(
1208
+ runWrangler(`kv:bulk put --namespace-id some-namespace-id keys.json`)
1209
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`
1210
+ "Unexpected JSON input from \\"keys.json\\".
1211
+ Each item in the array should be an object that matches:
1212
+
1213
+ interface KeyValue {
1214
+ key: string;
1215
+ value: string;
1216
+ expiration?: number;
1217
+ expiration_ttl?: number;
1218
+ metadata?: object;
1219
+ base64?: boolean;
1220
+ }
1221
+
1222
+ The item at index 0 is type: \\"number\\" - 123
1223
+ The item at index 1 is type: \\"string\\" - \\"a string\\"
1224
+ The item at index 2 is {\\"key\\":\\"someKey\\"}
1225
+ The item at index 3 is {\\"value\\":\\"someValue\\"}"
1226
+ `);
1227
+
1228
+ expect(std.out).toMatchInlineSnapshot(`""`);
1229
+ expect(std.warn).toMatchInlineSnapshot(`
1230
+ "Unexpected key-value properties in \\"keys.json\\".
1231
+ The item at index 4 contains unexpected properties: [\\"invalid\\"]."
1232
+ `);
1233
+ });
1234
+ });
1235
+
1236
+ describe("delete", () => {
1237
+ function mockDeleteRequest(
1238
+ expectedNamespaceId: string,
1239
+ expectedKeys: string[]
1240
+ ) {
1241
+ const requests = { count: 0 };
1242
+ setMockResponse(
1243
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId/bulk",
1244
+ "DELETE",
1245
+ ([_url, accountId, namespaceId], { headers, body }) => {
1246
+ requests.count++;
1247
+ expect(accountId).toEqual("some-account-id");
1248
+ expect(namespaceId).toEqual(expectedNamespaceId);
1249
+ expect(new Headers(headers ?? []).get("Content-Type")).toEqual(
1250
+ "application/json"
1251
+ );
1252
+ expect(JSON.parse(body as string)).toEqual(
1253
+ expectedKeys.slice(
1254
+ (requests.count - 1) * 5000,
1255
+ requests.count * 5000
1256
+ )
1257
+ );
1258
+ return null;
1259
+ }
1260
+ );
1261
+ return requests;
1262
+ }
1263
+
1264
+ it("should delete the keys parsed from a file", async () => {
1265
+ const keys = ["someKey1", "ns:someKey2"];
1266
+ writeFileSync("./keys.json", JSON.stringify(keys));
1267
+ mockConfirm({
1268
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1269
+ result: true,
1270
+ });
1271
+ const requests = mockDeleteRequest("some-namespace-id", keys);
1272
+ await runWrangler(
1273
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1274
+ );
1275
+ expect(requests.count).toEqual(1);
1276
+ expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1277
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1278
+ expect(std.err).toMatchInlineSnapshot(`""`);
1279
+ });
1280
+
1281
+ it("should delete the keys in batches of 5000 parsed from a file", async () => {
1282
+ const keys = new Array(12000).fill("some-key");
1283
+ writeFileSync("./keys.json", JSON.stringify(keys));
1284
+ mockConfirm({
1285
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1286
+ result: true,
1287
+ });
1288
+ const requests = mockDeleteRequest("some-namespace-id", keys);
1289
+ await runWrangler(
1290
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1291
+ );
1292
+ expect(requests.count).toEqual(3);
1293
+ expect(std.out).toMatchInlineSnapshot(`
1294
+ "Deleted 0 of 12000.
1295
+ Deleted 5000 of 12000.
1296
+ Deleted 10000 of 12000.
1297
+ Deleted 12000 of 12000.
1298
+ Success!"
1299
+ `);
1300
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1301
+ expect(std.err).toMatchInlineSnapshot(`""`);
1302
+ });
1303
+
1304
+ it("should not delete the keys if the user confirms no", async () => {
1305
+ const keys = ["someKey1", "ns:someKey2"];
1306
+ writeFileSync("./keys.json", JSON.stringify(keys));
1307
+ mockConfirm({
1308
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1309
+ result: false,
1310
+ });
1311
+ await runWrangler(
1312
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1313
+ );
1314
+ expect(std.out).toMatchInlineSnapshot(
1315
+ `"Not deleting keys read from \\"keys.json\\"."`
1316
+ );
1317
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1318
+ expect(std.err).toMatchInlineSnapshot(`""`);
1319
+ });
1320
+
1321
+ it("should delete the keys without asking if --force is provided", async () => {
1322
+ const keys = ["someKey1", "ns:someKey2"];
1323
+ writeFileSync("./keys.json", JSON.stringify(keys));
1324
+ const requests = mockDeleteRequest("some-namespace-id", keys);
1325
+ await runWrangler(
1326
+ `kv:bulk delete --namespace-id some-namespace-id keys.json --force`
1327
+ );
1328
+ expect(requests.count).toEqual(1);
1329
+ expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1330
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1331
+ expect(std.err).toMatchInlineSnapshot(`""`);
1332
+ });
1333
+
1334
+ it("should delete the keys without asking if -f is provided", async () => {
1335
+ const keys = ["someKey1", "ns:someKey2"];
1336
+ writeFileSync("./keys.json", JSON.stringify(keys));
1337
+ const requests = mockDeleteRequest("some-namespace-id", keys);
1338
+ await runWrangler(
1339
+ `kv:bulk delete --namespace-id some-namespace-id keys.json -f`
1340
+ );
1341
+ expect(requests.count).toEqual(1);
1342
+ expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1343
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1344
+ expect(std.err).toMatchInlineSnapshot(`""`);
1345
+ });
1346
+
1347
+ it("should error if the file is not a JSON array", async () => {
1348
+ const keys = 12354;
1349
+ writeFileSync("./keys.json", JSON.stringify(keys));
1350
+ mockConfirm({
1351
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1352
+ result: true,
1353
+ });
1354
+ await expect(
1355
+ runWrangler(
1356
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1357
+ )
1358
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`
1359
+ "Unexpected JSON input from \\"keys.json\\".
1360
+ Expected an array of strings but got:
1361
+ 12354"
1362
+ `);
1363
+ expect(std.out).toMatchInlineSnapshot(`""`);
1364
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1365
+ });
1366
+
1367
+ it("should error if the file contains non-string items", async () => {
1368
+ const keys = ["good", 12354, { key: "someKey" }, null];
1369
+ writeFileSync("./keys.json", JSON.stringify(keys));
1370
+ mockConfirm({
1371
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1372
+ result: true,
1373
+ });
1374
+ await expect(
1375
+ runWrangler(
1376
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1377
+ )
1378
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`
1379
+ "Unexpected JSON input from \\"keys.json\\".
1380
+ Expected an array of strings.
1381
+ The item at index 1 is type: \\"number\\" - 12354
1382
+ The item at index 2 is type: \\"object\\" - {\\"key\\":\\"someKey\\"}
1383
+ The item at index 3 is type: \\"object\\" - null"
1384
+ `);
1385
+ expect(std.out).toMatchInlineSnapshot(`""`);
1386
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1387
+ });
1388
+ });
1389
+ });
1390
+ });
1391
+
1392
+ function writeWranglerConfig() {
1393
+ writeFileSync(
1394
+ "./wrangler.toml",
1395
+ [
1396
+ 'name = "otherWorker"',
1397
+ "kv_namespaces = [",
1398
+ ' { binding = "someBinding", id = "bound-id", preview_id = "preview-bound-id" }',
1399
+ "]",
1400
+ "",
1401
+ "[env.some-environment]",
1402
+ "kv_namespaces = [",
1403
+ ' { binding = "someBinding", id = "env-bound-id", preview_id = "preview-env-bound-id" }',
1404
+ "]",
1405
+ ].join("\n"),
1406
+ "utf-8"
1407
+ );
1408
+ }