wrangler 0.0.0-e88a54e → 0.0.0-e8df68ee

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 (167) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +46 -15
  3. package/bin/wrangler.js +118 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +194 -143
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +23 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +172 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +127 -0
  17. package/templates/middleware/loader-sw.ts +228 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-d1-beta.ts +244 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +31 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/cli.d.ts +1726 -0
  41. package/wrangler-dist/cli.js +134048 -126481
  42. package/wrangler-dist/wasm-sync.wasm +0 -0
  43. package/import_meta_url.js +0 -3
  44. package/miniflare-config-stubs/.env.empty +0 -0
  45. package/miniflare-config-stubs/package.empty.json +0 -1
  46. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  47. package/miniflare-dist/index.mjs +0 -79
  48. package/miniflare-dist/index.mjs.map +0 -7
  49. package/pages/functions/buildWorker.ts +0 -62
  50. package/pages/functions/filepath-routing.test.ts +0 -223
  51. package/pages/functions/filepath-routing.ts +0 -181
  52. package/pages/functions/identifiers.ts +0 -78
  53. package/pages/functions/routes.ts +0 -151
  54. package/pages/functions/template-worker.ts +0 -130
  55. package/src/__tests__/configuration.test.ts +0 -2796
  56. package/src/__tests__/dev.test.tsx +0 -496
  57. package/src/__tests__/dev2.test.tsx +0 -154
  58. package/src/__tests__/guess-worker-format.test.ts +0 -58
  59. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  60. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  61. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  62. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  63. package/src/__tests__/helpers/mock-bin.ts +0 -36
  64. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  65. package/src/__tests__/helpers/mock-console.ts +0 -70
  66. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  69. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  70. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  71. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  72. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  73. package/src/__tests__/https-options.test.ts +0 -127
  74. package/src/__tests__/index.test.ts +0 -991
  75. package/src/__tests__/jest.setup.ts +0 -69
  76. package/src/__tests__/kv.test.ts +0 -1382
  77. package/src/__tests__/logout.test.ts +0 -52
  78. package/src/__tests__/package-manager.test.ts +0 -206
  79. package/src/__tests__/pages.test.ts +0 -44
  80. package/src/__tests__/parse.test.ts +0 -322
  81. package/src/__tests__/publish.test.ts +0 -2704
  82. package/src/__tests__/r2.test.ts +0 -198
  83. package/src/__tests__/route.test.ts +0 -45
  84. package/src/__tests__/secret.test.ts +0 -425
  85. package/src/__tests__/sentry.test.ts +0 -146
  86. package/src/__tests__/tail.test.ts +0 -564
  87. package/src/__tests__/whoami.test.tsx +0 -100
  88. package/src/bundle.ts +0 -142
  89. package/src/cfetch/index.ts +0 -104
  90. package/src/cfetch/internal.ts +0 -139
  91. package/src/cli.ts +0 -19
  92. package/src/config/README.md +0 -107
  93. package/src/config/config.ts +0 -218
  94. package/src/config/diagnostics.ts +0 -80
  95. package/src/config/environment.ts +0 -366
  96. package/src/config/index.ts +0 -62
  97. package/src/config/validation-helpers.ts +0 -486
  98. package/src/config/validation.ts +0 -1090
  99. package/src/create-worker-preview.ts +0 -166
  100. package/src/create-worker-upload-form.ts +0 -217
  101. package/src/dev/dev.tsx +0 -364
  102. package/src/dev/local.tsx +0 -232
  103. package/src/dev/remote.tsx +0 -203
  104. package/src/dev/use-esbuild.ts +0 -100
  105. package/src/dialogs.tsx +0 -77
  106. package/src/entry.ts +0 -208
  107. package/src/environment-variables.ts +0 -33
  108. package/src/https-options.ts +0 -122
  109. package/src/index.tsx +0 -2373
  110. package/src/inspect.ts +0 -617
  111. package/src/kv.ts +0 -319
  112. package/src/miniflare-cli/README.md +0 -30
  113. package/src/miniflare-cli/enum-keys.ts +0 -17
  114. package/src/miniflare-cli/index.ts +0 -37
  115. package/src/module-collection.ts +0 -258
  116. package/src/open-in-browser.ts +0 -25
  117. package/src/package-manager.ts +0 -126
  118. package/src/pages.tsx +0 -1047
  119. package/src/parse.ts +0 -183
  120. package/src/paths.ts +0 -26
  121. package/src/proxy.ts +0 -440
  122. package/src/publish.ts +0 -347
  123. package/src/r2.ts +0 -50
  124. package/src/reporting.ts +0 -131
  125. package/src/selfsigned.d.ts +0 -29
  126. package/src/sites.tsx +0 -280
  127. package/src/tail/filters.ts +0 -279
  128. package/src/tail/index.ts +0 -299
  129. package/src/tail/printing.ts +0 -62
  130. package/src/user.tsx +0 -1118
  131. package/src/whoami.tsx +0 -69
  132. package/src/worker.ts +0 -163
  133. package/templates/static-asset-facade.js +0 -47
  134. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  135. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  136. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  137. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  138. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  139. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  140. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  141. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  142. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  143. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  144. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  145. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  146. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  147. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  148. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  149. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  150. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  151. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  152. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  153. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  154. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  155. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  156. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  157. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  158. package/vendor/wrangler-mime/LICENSE +0 -21
  159. package/vendor/wrangler-mime/Mime.js +0 -97
  160. package/vendor/wrangler-mime/README.md +0 -187
  161. package/vendor/wrangler-mime/cli.js +0 -46
  162. package/vendor/wrangler-mime/index.js +0 -4
  163. package/vendor/wrangler-mime/lite.js +0 -4
  164. package/vendor/wrangler-mime/package.json +0 -52
  165. package/vendor/wrangler-mime/types/other.js +0 -1
  166. package/vendor/wrangler-mime/types/standard.js +0 -1
  167. package/wrangler-dist/cli.js.map +0 -7
package/src/index.tsx DELETED
@@ -1,2373 +0,0 @@
1
- import * as fs from "node:fs";
2
- import { writeFile, mkdir } from "node:fs/promises";
3
- import path from "node:path";
4
- import { setTimeout } from "node:timers/promises";
5
- import TOML from "@iarna/toml";
6
- import chalk from "chalk";
7
- import { findUp } from "find-up";
8
- import getPort from "get-port";
9
- import { render } from "ink";
10
- import React from "react";
11
- import onExit from "signal-exit";
12
- import supportsColor from "supports-color";
13
- import makeCLI from "yargs";
14
- import { version as wranglerVersion } from "../package.json";
15
- import { fetchResult } from "./cfetch";
16
- import { findWranglerToml, readConfig } from "./config";
17
- import { createWorkerUploadForm } from "./create-worker-upload-form";
18
- import Dev from "./dev/dev";
19
- import { confirm, prompt } from "./dialogs";
20
- import { getEntry } from "./entry";
21
- import {
22
- getNamespaceId,
23
- listNamespaces,
24
- listNamespaceKeys,
25
- putKeyValue,
26
- putBulkKeyValue,
27
- deleteBulkKeyValue,
28
- createNamespace,
29
- isValidNamespaceBinding,
30
- getKeyValue,
31
- isKeyValue,
32
- unexpectedKeyValueProps,
33
- } from "./kv";
34
- import { getPackageManager } from "./package-manager";
35
- import { pages } from "./pages";
36
- import { formatMessage, ParseError, parseJSON, readFileSync } from "./parse";
37
- import publish from "./publish";
38
- import { createR2Bucket, deleteR2Bucket, listR2Buckets } from "./r2";
39
- import { getAssetPaths } from "./sites";
40
- import {
41
- createTail,
42
- jsonPrintLogs,
43
- prettyPrintLogs,
44
- translateCLICommandToFilterMessage,
45
- } from "./tail";
46
- import {
47
- login,
48
- logout,
49
- listScopes,
50
- loginOrRefreshIfRequired,
51
- getAccountId,
52
- validateScopeKeys,
53
- } from "./user";
54
- import { whoami } from "./whoami";
55
-
56
- import type { Config } from "./config";
57
- import type { TailCLIFilters } from "./tail";
58
- import type { RawData } from "ws";
59
- import type { CommandModule } from "yargs";
60
- import type Yargs from "yargs";
61
-
62
- type ConfigPath = string | undefined;
63
-
64
- const resetColor = "\x1b[0m";
65
- const fgGreenColor = "\x1b[32m";
66
-
67
- function getRules(config: Config): Config["rules"] {
68
- const rules = config.rules ?? config.build?.upload?.rules ?? [];
69
-
70
- if (config.rules && config.build?.upload?.rules) {
71
- throw new Error(
72
- `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
73
- );
74
- }
75
-
76
- if (config.build?.upload?.rules) {
77
- console.warn(
78
- `Deprecation notice: The \`build.upload.rules\` config field is no longer used, the rules should be specified via the \`rules\` config field. Delete the \`build.upload\` field from the configuration file, and add this:
79
-
80
- ${TOML.stringify({ rules: config.build.upload.rules })}`
81
- );
82
- }
83
- return rules;
84
- }
85
-
86
- function printWranglerBanner() {
87
- // Let's not print this in tests
88
- if (typeof jest !== "undefined") {
89
- return;
90
- }
91
- const text = ` ⛅️ wrangler ${wranglerVersion} `;
92
-
93
- console.log(
94
- text +
95
- "\n" +
96
- (supportsColor.stdout
97
- ? chalk.hex("#FF8800")("-".repeat(text.length))
98
- : "-".repeat(text.length))
99
- );
100
- }
101
-
102
- function isLegacyEnv(args: unknown, config: Config): boolean {
103
- return (
104
- (args as { "legacy-env": boolean | undefined })["legacy-env"] ??
105
- config.legacy_env
106
- );
107
- }
108
-
109
- function getScriptName(
110
- args: { name: string | undefined; env: string | undefined },
111
- config: Config
112
- ): string | undefined {
113
- const shortScriptName = args.name ?? config.name;
114
- if (!shortScriptName) {
115
- return;
116
- }
117
-
118
- return isLegacyEnv(args, config)
119
- ? `${shortScriptName}${args.env ? `-${args.env}` : ""}`
120
- : shortScriptName;
121
- }
122
-
123
- /**
124
- * Ensure that a user is logged in, and a valid account_id is available.
125
- */
126
- async function requireAuth(
127
- config: Config,
128
- isInteractive = true
129
- ): Promise<string> {
130
- const loggedIn = await loginOrRefreshIfRequired(isInteractive);
131
- if (!loggedIn) {
132
- // didn't login, let's just quit
133
- throw new Error("Did not login, quitting...");
134
- }
135
- const accountId = config.account_id || (await getAccountId(isInteractive));
136
- if (!accountId) {
137
- throw new Error("No account id found, quitting...");
138
- }
139
-
140
- return accountId;
141
- }
142
-
143
- /**
144
- * Get a promise to the streamed input from stdin.
145
- *
146
- * This function can be used to grab the incoming stream of data from, say,
147
- * piping the output of another process into the wrangler process.
148
- */
149
- function readFromStdin(): Promise<string> {
150
- return new Promise((resolve, reject) => {
151
- const stdin = process.stdin;
152
- const chunks: string[] = [];
153
-
154
- // When there is data ready to be read, the `readable` event will be triggered.
155
- // In the handler for `readable` we call `read()` over and over until all the available data has been read.
156
- stdin.on("readable", () => {
157
- let chunk;
158
- while (null !== (chunk = stdin.read())) {
159
- chunks.push(chunk);
160
- }
161
- });
162
-
163
- // When the streamed data is complete the `end` event will be triggered.
164
- // In the handler for `end` we join the chunks together and resolve the promise.
165
- stdin.on("end", () => {
166
- resolve(chunks.join(""));
167
- });
168
-
169
- // If there is an `error` event then the handler will reject the promise.
170
- stdin.on("error", (err) => {
171
- reject(err);
172
- });
173
- });
174
- }
175
-
176
- // a helper to demand one of a set of options
177
- // via https://github.com/yargs/yargs/issues/1093#issuecomment-491299261
178
- function demandOneOfOption(...options: string[]) {
179
- return function (argv: Yargs.Arguments) {
180
- const count = options.filter((option) => argv[option]).length;
181
- const lastOption = options.pop();
182
-
183
- if (count === 0) {
184
- throw new CommandLineArgsError(
185
- `Exactly one of the arguments ${options.join(
186
- ", "
187
- )} and ${lastOption} is required`
188
- );
189
- } else if (count > 1) {
190
- throw new CommandLineArgsError(
191
- `Arguments ${options.join(
192
- ", "
193
- )} and ${lastOption} are mutually exclusive`
194
- );
195
- }
196
-
197
- return true;
198
- };
199
- }
200
-
201
- class CommandLineArgsError extends Error {}
202
- class DeprecationError extends Error {
203
- constructor(message: string) {
204
- super(`DEPRECATION WARNING:\n${message}`);
205
- }
206
- }
207
-
208
- export async function main(argv: string[]): Promise<void> {
209
- const wrangler = makeCLI(argv)
210
- // We handle errors ourselves in a try-catch around `yargs.parse`.
211
- // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
212
- // Otherwise we just log the error that was thrown without any "help info".
213
- .showHelpOnFail(false)
214
- .fail((msg, error) => {
215
- if (!error) {
216
- // If there is only a `msg` then this came from yargs own validation, so wrap in a `CommandLineArgsError`.
217
- error = new CommandLineArgsError(msg);
218
- }
219
- throw error;
220
- })
221
- .scriptName("wrangler")
222
- .wrap(null);
223
-
224
- // Default help command that supports the subcommands
225
- const subHelp: CommandModule = {
226
- command: ["*"],
227
- handler: async (args) => {
228
- setImmediate(() =>
229
- wrangler.parse([...args._.map((a) => `${a}`), "--help"])
230
- );
231
- },
232
- };
233
- wrangler.command(
234
- ["*"],
235
- false,
236
- () => {},
237
- (args) => {
238
- if (args._.length > 0) {
239
- throw new CommandLineArgsError(`Unknown command: ${args._}.`);
240
- } else {
241
- wrangler.showHelp("log");
242
- }
243
- }
244
- );
245
-
246
- // You will note that we use the form for all commands where we use the builder function
247
- // to define options and subcommands.
248
- // Further we return the result of this builder even though it's not completely necessary.
249
- // The reason is that it's required for type inference of the args in the handle function.
250
- // I wish we could enforce this pattern, but this comment will have to do for now.
251
- // (It's also annoying that choices[] doesn't get inferred as an enum. 🤷‍♂.)
252
-
253
- // [DEPRECATED] generate
254
- wrangler.command(
255
- // we definitely want to move away from us cloning github templates
256
- // we can do something better here, let's see
257
- "generate [name] [template]",
258
- false,
259
- (yargs) => {
260
- return yargs
261
- .positional("name", {
262
- describe: "Name of the Workers project",
263
- default: "worker",
264
- })
265
- .positional("template", {
266
- describe: "a link to a GitHub template",
267
- default: "https://github.com/cloudflare/worker-template",
268
- });
269
- },
270
- () => {
271
- // "👯 [DEPRECATED]. Scaffold a Cloudflare Workers project from a public GitHub repository.",
272
- throw new DeprecationError(
273
- "`wrangler generate` has been deprecated, please refer to https://github.com/cloudflare/wrangler2/blob/main/docs/deprecations.md#generate for alternatives"
274
- );
275
- }
276
- );
277
-
278
- // init
279
- wrangler.command(
280
- "init [name]",
281
- "📥 Create a wrangler.toml configuration file",
282
- (yargs) => {
283
- return yargs
284
- .positional("name", {
285
- describe: "The name of your worker",
286
- type: "string",
287
- })
288
- .option("yes", {
289
- describe: 'Answer "yes" to any prompts for new projects',
290
- type: "boolean",
291
- alias: "y",
292
- });
293
- },
294
- async (args) => {
295
- printWranglerBanner();
296
- if ("type" in args) {
297
- let message = "The --type option is no longer supported.";
298
- if (args.type === "webpack") {
299
- message +=
300
- "\nIf you wish to use webpack then you will need to create a custom build.";
301
- // TODO: Add a link to docs
302
- }
303
- throw new CommandLineArgsError(message);
304
- }
305
-
306
- // TODO: make sure args.name is a valid identifier for a worker name
307
-
308
- const creationDirectory = path.join(process.cwd(), args.name ?? "");
309
-
310
- const packageManager = await getPackageManager(creationDirectory);
311
-
312
- // TODO: ask which directory to make the worker in (defaults to args.name)
313
- // TODO: if args.name isn't provided, ask what to name the worker
314
-
315
- const wranglerTomlDestination = path.join(
316
- creationDirectory,
317
- "./wrangler.toml"
318
- );
319
- let justCreatedWranglerToml = false;
320
- const workerName =
321
- args.name || path.basename(path.resolve(process.cwd()));
322
- if (fs.existsSync(wranglerTomlDestination)) {
323
- console.warn(`${wranglerTomlDestination} file already exists!`);
324
- const shouldContinue = await confirm(
325
- "Do you want to continue initializing this project?"
326
- );
327
- if (!shouldContinue) {
328
- return;
329
- }
330
- } else {
331
- await mkdir(creationDirectory, { recursive: true });
332
- const compatibilityDate = new Date().toISOString().substring(0, 10);
333
- try {
334
- await writeFile(
335
- wranglerTomlDestination,
336
- TOML.stringify({
337
- name: workerName,
338
- compatibility_date: compatibilityDate,
339
- }) + "\n"
340
- );
341
- console.log(`✨ Successfully created wrangler.toml`);
342
- justCreatedWranglerToml = true;
343
- } catch (err) {
344
- throw new Error(
345
- `Failed to create wrangler.toml.\n${(err as Error).message ?? err}`
346
- );
347
- }
348
- }
349
-
350
- let pathToPackageJson = await findUp("package.json");
351
- let shouldCreatePackageJson = false;
352
- const yesFlag = args.yes ?? false;
353
- if (!pathToPackageJson) {
354
- // If no package.json exists, ask to create one
355
- shouldCreatePackageJson =
356
- yesFlag ||
357
- (await confirm(
358
- "No package.json found. Would you like to create one?"
359
- ));
360
-
361
- if (shouldCreatePackageJson) {
362
- await writeFile(
363
- path.join(creationDirectory, "./package.json"),
364
- JSON.stringify(
365
- {
366
- name: workerName,
367
- version: "0.0.0",
368
- devDependencies: {
369
- wrangler: wranglerVersion,
370
- },
371
- private: true,
372
- },
373
- null,
374
- " "
375
- ) + "\n"
376
- );
377
- await packageManager.install();
378
- console.log(`✨ Created package.json`);
379
- pathToPackageJson = path.join(creationDirectory, "package.json");
380
- } else {
381
- return;
382
- }
383
- } else {
384
- // If package.json exists and wrangler isn't installed,
385
- // then ask to add wrangler to devDependencies
386
- const packageJson = parseJSON(
387
- readFileSync(pathToPackageJson),
388
- pathToPackageJson
389
- );
390
- if (
391
- !(
392
- packageJson.devDependencies?.wrangler ||
393
- packageJson.dependencies?.wrangler
394
- )
395
- ) {
396
- const shouldInstall =
397
- yesFlag ||
398
- (await confirm(
399
- "Would you like to install wrangler into your package.json?"
400
- ));
401
- if (shouldInstall) {
402
- await packageManager.addDevDeps(`wrangler@${wranglerVersion}`);
403
- console.log(`✨ Installed wrangler`);
404
- }
405
- }
406
- }
407
-
408
- let isTypescriptProject = false;
409
- let pathToTSConfig = await findUp("tsconfig.json");
410
- if (!pathToTSConfig) {
411
- // If there's no tsconfig, offer to create one
412
- // and install @cloudflare/workers-types
413
- if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
414
- isTypescriptProject = true;
415
- await writeFile(
416
- path.join(creationDirectory, "./tsconfig.json"),
417
- readFileSync(path.join(__dirname, "../templates/tsconfig.json"))
418
- );
419
- await packageManager.addDevDeps(
420
- "@cloudflare/workers-types",
421
- "typescript"
422
- );
423
-
424
- console.log(
425
- `✨ Created tsconfig.json, installed @cloudflare/workers-types into devDependencies`
426
- );
427
- pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
428
- }
429
- } else {
430
- isTypescriptProject = true;
431
- // If there's a tsconfig, check if @cloudflare/workers-types
432
- // is already installed, and offer to install it if not
433
- const packageJson = parseJSON(
434
- readFileSync(pathToPackageJson),
435
- pathToPackageJson
436
- );
437
- if (
438
- !(
439
- packageJson.devDependencies?.["@cloudflare/workers-types"] ||
440
- packageJson.dependencies?.["@cloudflare/workers-types"]
441
- )
442
- ) {
443
- const shouldInstall = await confirm(
444
- "Would you like to install the type definitions for Workers into your package.json?"
445
- );
446
- if (shouldInstall) {
447
- await packageManager.addDevDeps("@cloudflare/workers-types");
448
- // We don't update the tsconfig.json because
449
- // it could be complicated in existing projects
450
- // and we don't want to break them. Instead, we simply
451
- // tell the user that they need to update their tsconfig.json
452
- console.log(
453
- `✨ Installed @cloudflare/workers-types.\nPlease add "@cloudflare/workers-types" to compilerOptions.types in your tsconfig.json`
454
- );
455
- }
456
- }
457
- }
458
-
459
- const packageJsonContent = parseJSON(
460
- readFileSync(pathToPackageJson),
461
- pathToPackageJson
462
- );
463
- const shouldWritePackageJsonScripts =
464
- !packageJsonContent.scripts?.start &&
465
- !packageJsonContent.scripts?.publish &&
466
- shouldCreatePackageJson;
467
-
468
- async function writePackageJsonScriptsAndUpdateWranglerToml(
469
- isWritingScripts: boolean,
470
- isCreatingWranglerToml: boolean,
471
- packagePath: string,
472
- scriptPath: string
473
- ) {
474
- if (isCreatingWranglerToml) {
475
- // rewrite wrangler.toml with main = "path/to/script"
476
- const parsedWranglerToml = TOML.parse(
477
- readFileSync(wranglerTomlDestination)
478
- );
479
- fs.writeFileSync(
480
- wranglerTomlDestination,
481
- TOML.stringify({
482
- name: parsedWranglerToml.name,
483
- main: scriptPath,
484
- compatibility_date: parsedWranglerToml.compatibility_date,
485
- })
486
- );
487
- }
488
- const isNamedWorker =
489
- isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
490
-
491
- if (isWritingScripts) {
492
- await writeFile(
493
- packagePath,
494
- JSON.stringify(
495
- {
496
- ...packageJsonContent,
497
- scripts: {
498
- ...packageJsonContent.scripts,
499
- start: isCreatingWranglerToml
500
- ? `wrangler dev`
501
- : `wrangler dev ${scriptPath}`,
502
- publish: isCreatingWranglerToml
503
- ? `wrangler publish`
504
- : `wrangler publish ${scriptPath}`,
505
- },
506
- },
507
- null,
508
- 2
509
- ) + "\n"
510
- );
511
- console.log(
512
- `\nTo start developing your Worker, run \`${
513
- isNamedWorker ? `cd ${args.name} && ` : ""
514
- }npm start\``
515
- );
516
- console.log(
517
- `To publish your Worker to the Internet, run \`npm run publish\``
518
- );
519
- } else {
520
- console.log(
521
- `\nTo start developing your Worker, run \`npx wrangler dev\`${
522
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
523
- }`
524
- );
525
- console.log(
526
- `To publish your Worker to the Internet, run \`npx wrangler publish\`${
527
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
528
- }`
529
- );
530
- }
531
- }
532
-
533
- if (isTypescriptProject) {
534
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
535
- let shouldCreateSource = false;
536
-
537
- shouldCreateSource =
538
- yesFlag ||
539
- (await confirm(
540
- `Would you like to create a Worker at src/index.ts?`
541
- ));
542
-
543
- if (shouldCreateSource) {
544
- await mkdir(path.join(creationDirectory, "./src"), {
545
- recursive: true,
546
- });
547
- await writeFile(
548
- path.join(creationDirectory, "./src/index.ts"),
549
- readFileSync(path.join(__dirname, "../templates/new-worker.ts"))
550
- );
551
-
552
- console.log(`✨ Created src/index.ts`);
553
-
554
- await writePackageJsonScriptsAndUpdateWranglerToml(
555
- shouldWritePackageJsonScripts,
556
- justCreatedWranglerToml,
557
- pathToPackageJson,
558
- "src/index.ts"
559
- );
560
- }
561
- }
562
- } else {
563
- if (!fs.existsSync("./src/index.js")) {
564
- const shouldCreateSource = await confirm(
565
- `Would you like to create a Worker at src/index.js?`
566
- );
567
- if (shouldCreateSource) {
568
- await mkdir(path.join(creationDirectory, "./src"), {
569
- recursive: true,
570
- });
571
- await writeFile(
572
- path.join(path.join(creationDirectory, "./src/index.js")),
573
- readFileSync(path.join(__dirname, "../templates/new-worker.js"))
574
- );
575
-
576
- console.log(`✨ Created src/index.js`);
577
-
578
- await writePackageJsonScriptsAndUpdateWranglerToml(
579
- shouldWritePackageJsonScripts,
580
- justCreatedWranglerToml,
581
- pathToPackageJson,
582
- "src/index.js"
583
- );
584
- }
585
- }
586
- }
587
- }
588
- );
589
-
590
- // build
591
- wrangler.command(
592
- "build",
593
- false,
594
- (yargs) => {
595
- return yargs.option("env", {
596
- describe: "Perform on a specific environment",
597
- });
598
- },
599
- () => {
600
- // "[DEPRECATED] 🦀 Build your project (if applicable)",
601
- throw new DeprecationError(
602
- "`wrangler build` has been deprecated, please refer to https://github.com/cloudflare/wrangler2/blob/main/docs/deprecations.md#build for alternatives"
603
- );
604
- }
605
- );
606
-
607
- // login
608
- wrangler.command(
609
- // this needs scopes as an option?
610
- "login",
611
- false, // we don't need to show this in the menu
612
- // "🔓 Login to Cloudflare",
613
- (yargs) => {
614
- // TODO: This needs some copy editing
615
- // I mean, this entire app does, but this too.
616
- return yargs
617
- .option("scopes-list", {
618
- describe: "List all the available OAuth scopes with descriptions",
619
- })
620
- .option("scopes", {
621
- describe: "Pick the set of applicable OAuth scopes when logging in",
622
- array: true,
623
- type: "string",
624
- });
625
-
626
- // TODO: scopes
627
- },
628
- async (args) => {
629
- printWranglerBanner();
630
- if (args["scopes-list"]) {
631
- listScopes();
632
- return;
633
- }
634
- if (args.scopes) {
635
- if (args.scopes.length === 0) {
636
- // don't allow no scopes to be passed, that would be weird
637
- listScopes();
638
- return;
639
- }
640
- if (!validateScopeKeys(args.scopes)) {
641
- throw new CommandLineArgsError(
642
- `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
643
- );
644
- }
645
- await login({ scopes: args.scopes });
646
- return;
647
- }
648
- await login();
649
-
650
- // TODO: would be nice if it optionally saved login
651
- // credentials inside node_modules/.cache or something
652
- // this way you could have multiple users on a single machine
653
- }
654
- );
655
-
656
- // logout
657
- wrangler.command(
658
- // this needs scopes as an option?
659
- "logout",
660
- false, // we don't need to show this in the menu
661
- // "🚪 Logout from Cloudflare",
662
- () => {},
663
- async () => {
664
- printWranglerBanner();
665
- await logout();
666
- }
667
- );
668
-
669
- // whoami
670
- wrangler.command(
671
- "whoami",
672
- "🕵️ Retrieve your user info and test your auth config",
673
- () => {},
674
- async () => {
675
- printWranglerBanner();
676
- await whoami();
677
- }
678
- );
679
-
680
- // config
681
- wrangler.command(
682
- "config",
683
- false,
684
- () => {},
685
- () => {
686
- // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
687
- throw new DeprecationError(
688
- "`wrangler config` has been deprecated, please refer to https://github.com/cloudflare/wrangler2/blob/main/docs/deprecations.md#config for alternatives"
689
- );
690
- }
691
- );
692
-
693
- // dev
694
- wrangler.command(
695
- "dev [script]",
696
- "👂 Start a local server for developing your worker",
697
- (yargs) => {
698
- return yargs
699
- .positional("script", {
700
- describe: "The path to an entry point for your worker",
701
- type: "string",
702
- })
703
- .option("name", {
704
- describe: "Name of the worker",
705
- type: "string",
706
- })
707
- .option("format", {
708
- choices: ["modules", "service-worker"] as const,
709
- describe: "Choose an entry type",
710
- })
711
- .option("env", {
712
- describe: "Perform on a specific environment",
713
- type: "string",
714
- alias: "e",
715
- })
716
- .option("compatibility-date", {
717
- describe: "Date to use for compatibility checks",
718
- type: "string",
719
- })
720
- .option("compatibility-flags", {
721
- describe: "Flags to use for compatibility checks",
722
- type: "array",
723
- alias: "compatibility-flag",
724
- })
725
- .option("latest", {
726
- describe: "Use the latest version of the worker runtime",
727
- type: "boolean",
728
- default: true,
729
- })
730
- .option("ip", {
731
- describe: "IP address to listen on, defaults to `localhost`",
732
- type: "string",
733
- })
734
- .option("port", {
735
- describe: "Port to listen on",
736
- type: "number",
737
- })
738
- .option("inspector-port", {
739
- describe: "Port for devtools to connect to",
740
- type: "number",
741
- })
742
- .option("routes", {
743
- describe: "Routes to upload",
744
- alias: "route",
745
- type: "array",
746
- })
747
- .option("host", {
748
- type: "string",
749
- describe:
750
- "Host to forward requests to, defaults to the zone of project",
751
- })
752
- .option("local-protocol", {
753
- describe: "Protocol to listen to requests on, defaults to http.",
754
- choices: ["http", "https"] as const,
755
- })
756
- .option("experimental-public", {
757
- describe: "Static assets to be served",
758
- type: "string",
759
- })
760
- .option("site", {
761
- describe: "Root folder of static assets for Workers Sites",
762
- type: "string",
763
- })
764
- .option("site-include", {
765
- describe:
766
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
767
- type: "string",
768
- array: true,
769
- })
770
- .option("site-exclude", {
771
- describe:
772
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
773
- type: "string",
774
- array: true,
775
- })
776
- .option("upstream-protocol", {
777
- describe:
778
- "Protocol to forward requests to host on, defaults to https.",
779
- choices: ["http", "https"] as const,
780
- })
781
- .option("jsx-factory", {
782
- describe: "The function that is called for each JSX element",
783
- type: "string",
784
- })
785
- .option("jsx-fragment", {
786
- describe: "The function that is called for each JSX fragment",
787
- type: "string",
788
- })
789
- .option("local", {
790
- alias: "l",
791
- describe: "Run on my machine",
792
- type: "boolean",
793
- default: false, // I bet this will a point of contention. We'll revisit it.
794
- })
795
- .option("experimental-enable-local-persistence", {
796
- describe: "Enable persistence for this session (only for local mode)",
797
- type: "boolean",
798
- });
799
- },
800
- async (args) => {
801
- printWranglerBanner();
802
- const configPath =
803
- (args.config as ConfigPath) ||
804
- (args.script && findWranglerToml(path.dirname(args.script)));
805
- const config = readConfig(configPath, args.env);
806
- const entry = await getEntry(args, config, "dev");
807
-
808
- if (args["experimental-public"]) {
809
- console.warn(
810
- "🚨 The --experimental-public field is experimental and will change in the future."
811
- );
812
- }
813
-
814
- if (args.public) {
815
- throw new Error(
816
- "🚨 The --public field has been renamed to --experimental-public, and will change behaviour in the future."
817
- );
818
- }
819
-
820
- const upstreamProtocol =
821
- (args["upstream-protocol"] as "http" | "https") ||
822
- config.dev.upstream_protocol;
823
- if (upstreamProtocol === "http") {
824
- console.warn(
825
- "Setting upstream-protocol to http is not currently implemented.\n" +
826
- "If this is required in your project, please add your use case to the following issue:\n" +
827
- "https://github.com/cloudflare/wrangler2/issues/583."
828
- );
829
- }
830
-
831
- const accountId = !args.local ? await requireAuth(config) : undefined;
832
-
833
- // TODO: if worker_dev = false and no routes, then error (only for dev)
834
-
835
- /**
836
- * Given something that resembles a URL,
837
- * try to extract a host from it
838
- */
839
- function getHost(urlLike: string): string | undefined {
840
- if (
841
- !(urlLike.startsWith("http://") || urlLike.startsWith("https://"))
842
- ) {
843
- urlLike = "http://" + urlLike;
844
- }
845
- return new URL(urlLike).host;
846
- }
847
-
848
- /**
849
- * Given something that resembles a host,
850
- * try to infer a zone id from it
851
- */
852
- async function getZoneId(host: string): Promise<string | undefined> {
853
- const zones = await fetchResult<{ id: string }[]>(
854
- `/zones`,
855
- {},
856
- new URLSearchParams({ name: host })
857
- );
858
- return zones[0]?.id;
859
- }
860
-
861
- const hostLike =
862
- args.host ||
863
- config.dev.host ||
864
- (args.routes && args.routes[0]) ||
865
- config.route ||
866
- (config.routes && config.routes[0]);
867
-
868
- // When we're given a host (in one of the above ways), we do 2 things:
869
- // - We try to extract a host from it
870
- // - We try to get a zone id from the host
871
- //
872
- // So it turns out it's particularly hard to get a 'valid' domain
873
- // from a string, so we don't even try to validate TLDs, etc.
874
- // Once we get something that looks like w.x.y.z-ish, we then try to
875
- // get a zone id for it, by lopping off subdomains until we get a hit
876
- // from the API. That's it!
877
-
878
- const host = typeof hostLike === "string" ? getHost(hostLike) : undefined;
879
-
880
- let zoneId: string | undefined;
881
- const hostPieces = typeof host === "string" ? host.split(".") : undefined;
882
-
883
- while (hostPieces && hostPieces.length > 1) {
884
- zoneId = await getZoneId(hostPieces.join("."));
885
- if (zoneId) break;
886
- hostPieces.shift();
887
- }
888
- if (host && !zoneId) {
889
- throw new Error(`Could not find zone for ${hostLike}`);
890
- }
891
-
892
- const zone =
893
- typeof zoneId === "string" && typeof host === "string"
894
- ? {
895
- host,
896
- id: zoneId,
897
- }
898
- : undefined;
899
-
900
- const { waitUntilExit } = render(
901
- <Dev
902
- name={getScriptName(args, config)}
903
- entry={entry}
904
- env={args.env}
905
- zone={zone}
906
- rules={getRules(config)}
907
- legacyEnv={isLegacyEnv(args, config)}
908
- buildCommand={config.build || {}}
909
- initialMode={args.local ? "local" : "remote"}
910
- jsxFactory={args["jsx-factory"] || config.jsx_factory}
911
- jsxFragment={args["jsx-fragment"] || config.jsx_fragment}
912
- upstreamProtocol={upstreamProtocol}
913
- localProtocol={
914
- // The typings are not quite clever enough to handle element accesses, only property accesses,
915
- // so we need to cast here.
916
- (args["local-protocol"] as "http" | "https") ||
917
- config.dev.local_protocol
918
- }
919
- enableLocalPersistence={
920
- args["experimental-enable-local-persistence"] || false
921
- }
922
- accountId={accountId}
923
- assetPaths={getAssetPaths(
924
- config,
925
- args.site,
926
- args.siteInclude,
927
- args.siteExclude
928
- )}
929
- port={
930
- args.port || config.dev?.port || (await getPort({ port: 8787 }))
931
- }
932
- ip={args.ip || config.dev.ip}
933
- inspectorPort={
934
- args["inspector-port"] ?? (await getPort({ port: 9229 }))
935
- }
936
- public={args["experimental-public"]}
937
- compatibilityDate={
938
- args["compatibility-date"] ||
939
- config.compatibility_date ||
940
- new Date().toISOString().substring(0, 10)
941
- }
942
- compatibilityFlags={
943
- (args["compatibility-flags"] as string[]) ||
944
- config.compatibility_flags
945
- }
946
- usageModel={config.usage_model}
947
- bindings={{
948
- kv_namespaces: config.kv_namespaces?.map(
949
- ({ binding, preview_id, id: _id }) => {
950
- // In `dev`, we make folks use a separate kv namespace called
951
- // `preview_id` instead of `id` so that they don't
952
- // break production data. So here we check that a `preview_id`
953
- // has actually been configured.
954
- // This whole block of code will be obsoleted in the future
955
- // when we have copy-on-write for previews on edge workers.
956
- if (!preview_id) {
957
- // TODO: This error has to be a _lot_ better, ideally just asking
958
- // to create a preview namespace for the user automatically
959
- throw new Error(
960
- `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
961
- ); // Ugh, I really don't like this message very much
962
- }
963
- return {
964
- binding,
965
- id: preview_id,
966
- };
967
- }
968
- ),
969
- vars: config.vars,
970
- wasm_modules: config.wasm_modules,
971
- text_blobs: config.text_blobs,
972
- durable_objects: config.durable_objects,
973
- r2_buckets: config.r2_buckets,
974
- unsafe: config.unsafe?.bindings,
975
- }}
976
- />
977
- );
978
- await waitUntilExit();
979
- }
980
- );
981
-
982
- // publish
983
- wrangler.command(
984
- "publish [script]",
985
- "🆙 Publish your Worker to Cloudflare.",
986
- (yargs) => {
987
- return yargs
988
- .option("env", {
989
- type: "string",
990
- describe: "Perform on a specific environment",
991
- alias: "e",
992
- })
993
- .positional("script", {
994
- describe: "The path to an entry point for your worker",
995
- type: "string",
996
- })
997
- .option("name", {
998
- describe: "Name of the worker",
999
- type: "string",
1000
- })
1001
- .option("format", {
1002
- choices: ["modules", "service-worker"] as const,
1003
- describe: "Choose an entry type",
1004
- })
1005
- .option("compatibility-date", {
1006
- describe: "Date to use for compatibility checks",
1007
- type: "string",
1008
- })
1009
- .option("compatibility-flags", {
1010
- describe: "Flags to use for compatibility checks",
1011
- type: "array",
1012
- alias: "compatibility-flag",
1013
- })
1014
- .option("latest", {
1015
- describe: "Use the latest version of the worker runtime",
1016
- type: "boolean",
1017
- default: false,
1018
- })
1019
- .option("experimental-public", {
1020
- describe: "Static assets to be served",
1021
- type: "string",
1022
- })
1023
- .option("site", {
1024
- describe: "Root folder of static assets for Workers Sites",
1025
- type: "string",
1026
- })
1027
- .option("site-include", {
1028
- describe:
1029
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
1030
- type: "string",
1031
- array: true,
1032
- })
1033
- .option("site-exclude", {
1034
- describe:
1035
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
1036
- type: "string",
1037
- array: true,
1038
- })
1039
- .option("triggers", {
1040
- describe: "cron schedules to attach",
1041
- alias: ["schedule", "schedules"],
1042
- type: "array",
1043
- })
1044
- .option("routes", {
1045
- describe: "Routes to upload",
1046
- alias: "route",
1047
- type: "array",
1048
- })
1049
- .option("jsx-factory", {
1050
- describe: "The function that is called for each JSX element",
1051
- type: "string",
1052
- })
1053
- .option("jsx-fragment", {
1054
- describe: "The function that is called for each JSX fragment",
1055
- type: "string",
1056
- });
1057
- },
1058
- async (args) => {
1059
- printWranglerBanner();
1060
- if (args["experimental-public"]) {
1061
- console.warn(
1062
- "🚨 The --experimental-public field is experimental and will change in the future."
1063
- );
1064
- }
1065
- if (args.public) {
1066
- throw new Error(
1067
- "🚨 The --public field has been renamed to --experimental-public, and will change behaviour in the future."
1068
- );
1069
- }
1070
-
1071
- const configPath =
1072
- (args.config as ConfigPath) ||
1073
- (args.script && findWranglerToml(path.dirname(args.script)));
1074
- const config = readConfig(configPath, args.env);
1075
- const entry = await getEntry(args, config, "publish");
1076
-
1077
- if (args.latest) {
1078
- console.warn(
1079
- "⚠️ Using the latest version of the Workers runtime. To silence this warning, please choose a specific version of the runtime with --compatibility-date, or add a compatibility_date to your wrangler.toml.\n"
1080
- );
1081
- }
1082
-
1083
- const accountId = await requireAuth(config);
1084
-
1085
- const assetPaths = getAssetPaths(
1086
- config,
1087
- args["experimental-public"] || args.site,
1088
- args.siteInclude,
1089
- args.siteExclude
1090
- );
1091
- await publish({
1092
- config,
1093
- accountId,
1094
- name: getScriptName(args, config),
1095
- rules: getRules(config),
1096
- entry,
1097
- env: args.env,
1098
- compatibilityDate: args.latest
1099
- ? new Date().toISOString().substring(0, 10)
1100
- : args["compatibility-date"],
1101
- compatibilityFlags: args["compatibility-flags"] as string[],
1102
- triggers: args.triggers,
1103
- jsxFactory: args["jsx-factory"],
1104
- jsxFragment: args["jsx-fragment"],
1105
- routes: args.routes,
1106
- assetPaths,
1107
- legacyEnv: isLegacyEnv(args, config),
1108
- experimentalPublic: args["experimental-public"] !== undefined,
1109
- });
1110
- }
1111
- );
1112
-
1113
- // tail
1114
- wrangler.command(
1115
- "tail [name]",
1116
- "🦚 Starts a log tailing session for a published Worker.",
1117
- (yargs) => {
1118
- return (
1119
- yargs
1120
- .positional("name", {
1121
- describe: "Name of the worker",
1122
- type: "string",
1123
- })
1124
- // TODO: auto-detect if this should be json or pretty based on atty
1125
- .option("format", {
1126
- default: "json",
1127
- choices: ["json", "pretty"],
1128
- describe: "The format of log entries",
1129
- })
1130
- .option("status", {
1131
- choices: ["ok", "error", "canceled"],
1132
- describe: "Filter by invocation status",
1133
- array: true,
1134
- })
1135
- .option("header", {
1136
- type: "string",
1137
- describe: "Filter by HTTP header",
1138
- })
1139
- .option("method", {
1140
- type: "string",
1141
- describe: "Filter by HTTP method",
1142
- array: true,
1143
- })
1144
- .option("sampling-rate", {
1145
- type: "number",
1146
- describe: "Adds a percentage of requests to log sampling rate",
1147
- })
1148
- .option("search", {
1149
- type: "string",
1150
- describe: "Filter by a text match in console.log messages",
1151
- })
1152
- .option("ip", {
1153
- type: "string",
1154
- describe:
1155
- 'Filter by the IP address the request originates from. Use "self" to filter for your own IP',
1156
- array: true,
1157
- })
1158
- .option("env", {
1159
- type: "string",
1160
- describe: "Perform on a specific environment",
1161
- alias: "e",
1162
- })
1163
- .option("debug", {
1164
- type: "boolean",
1165
- hidden: true,
1166
- default: false,
1167
- describe:
1168
- "If a log would have been filtered out, send it through anyway alongside the filter which would have blocked it.",
1169
- })
1170
- );
1171
- },
1172
- async (args) => {
1173
- if (args.format === "pretty") {
1174
- printWranglerBanner();
1175
- }
1176
- const config = readConfig(args.config as ConfigPath, args.env);
1177
-
1178
- const scriptName = getScriptName(args, config);
1179
-
1180
- if (!scriptName) {
1181
- throw new Error("Missing script name");
1182
- }
1183
-
1184
- const accountId = await requireAuth(config);
1185
-
1186
- const cliFilters: TailCLIFilters = {
1187
- status: args.status as ("ok" | "error" | "canceled")[],
1188
- header: args.header,
1189
- method: args.method,
1190
- samplingRate: args["sampling-rate"],
1191
- search: args.search,
1192
- clientIp: args.ip,
1193
- };
1194
-
1195
- const filters = translateCLICommandToFilterMessage(
1196
- cliFilters,
1197
- args.debug
1198
- );
1199
-
1200
- const { tail, expiration, deleteTail } = await createTail(
1201
- accountId,
1202
- scriptName,
1203
- filters,
1204
- !isLegacyEnv(args, config) ? args.env : undefined
1205
- );
1206
-
1207
- const scriptDisplayName = `${scriptName}${
1208
- args.env && !isLegacyEnv(args, config) ? ` (${args.env})` : ""
1209
- }`;
1210
-
1211
- console.log(
1212
- `successfully created tail, expires at ${expiration.toLocaleString()}`
1213
- );
1214
-
1215
- onExit(async () => {
1216
- tail.terminate();
1217
- await deleteTail();
1218
- });
1219
-
1220
- const printLog: (data: RawData) => void =
1221
- args.format === "pretty" ? prettyPrintLogs : jsonPrintLogs;
1222
-
1223
- tail.on("message", printLog);
1224
-
1225
- while (tail.readyState !== tail.OPEN) {
1226
- switch (tail.readyState) {
1227
- case tail.CONNECTING:
1228
- await setTimeout(100);
1229
- break;
1230
- case tail.CLOSING:
1231
- await setTimeout(100);
1232
- break;
1233
- case tail.CLOSED:
1234
- throw new Error(
1235
- `Connection to ${scriptDisplayName} closed unexpectedly.`
1236
- );
1237
- }
1238
- }
1239
-
1240
- console.log(`Connected to ${scriptDisplayName}, waiting for logs...`);
1241
-
1242
- tail.on("close", async () => {
1243
- tail.terminate();
1244
- await deleteTail();
1245
- });
1246
- }
1247
- );
1248
-
1249
- // preview
1250
- wrangler.command(
1251
- "preview [method] [body]",
1252
- false,
1253
- (yargs) => {
1254
- return yargs
1255
- .positional("method", {
1256
- type: "string",
1257
- describe: "Type of request to preview your worker",
1258
- })
1259
- .positional("body", {
1260
- type: "string",
1261
- describe: "Body string to post to your preview worker request.",
1262
- })
1263
- .option("env", {
1264
- type: "string",
1265
- describe: "Perform on a specific environment",
1266
- })
1267
- .option("watch", {
1268
- default: true,
1269
- describe: "Enable live preview",
1270
- type: "boolean",
1271
- });
1272
- },
1273
- async (args) => {
1274
- if (args.method || args.body) {
1275
- throw new DeprecationError(
1276
- "The `wrangler preview` command has been deprecated.\n" +
1277
- "Try using `wrangler dev` to to try out a worker during development.\n"
1278
- );
1279
- }
1280
-
1281
- // Delegate to `wrangler dev`
1282
- console.warn(
1283
- "***************************************************\n" +
1284
- "The `wrangler preview` command has been deprecated.\n" +
1285
- "Attempting to run `wrangler dev` instead.\n" +
1286
- "***************************************************\n"
1287
- );
1288
-
1289
- const config = readConfig(args.config as ConfigPath, args.env);
1290
- const entry = await getEntry({}, config, "dev");
1291
-
1292
- const accountId = await requireAuth(config);
1293
-
1294
- const { waitUntilExit } = render(
1295
- <Dev
1296
- name={config.name}
1297
- entry={entry}
1298
- rules={getRules(config)}
1299
- env={args.env}
1300
- zone={undefined}
1301
- legacyEnv={isLegacyEnv(args, config)}
1302
- buildCommand={config.build || {}}
1303
- initialMode={args.local ? "local" : "remote"}
1304
- jsxFactory={config.jsx_factory}
1305
- jsxFragment={config.jsx_fragment}
1306
- upstreamProtocol={config.dev.upstream_protocol}
1307
- localProtocol={config.dev.local_protocol}
1308
- enableLocalPersistence={false}
1309
- accountId={accountId}
1310
- assetPaths={undefined}
1311
- port={config.dev?.port}
1312
- ip={config.dev.ip}
1313
- public={undefined}
1314
- compatibilityDate={
1315
- config.compatibility_date ||
1316
- new Date().toISOString().substring(0, 10)
1317
- }
1318
- compatibilityFlags={
1319
- (args["compatibility-flags"] as string[]) ||
1320
- config.compatibility_flags
1321
- }
1322
- usageModel={config.usage_model}
1323
- bindings={{
1324
- kv_namespaces: config.kv_namespaces?.map(
1325
- ({ binding, preview_id, id: _id }) => {
1326
- // In `dev`, we make folks use a separate kv namespace called
1327
- // `preview_id` instead of `id` so that they don't
1328
- // break production data. So here we check that a `preview_id`
1329
- // has actually been configured.
1330
- // This whole block of code will be obsoleted in the future
1331
- // when we have copy-on-write for previews on edge workers.
1332
- if (!preview_id) {
1333
- // TODO: This error has to be a _lot_ better, ideally just asking
1334
- // to create a preview namespace for the user automatically
1335
- throw new Error(
1336
- `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
1337
- ); // Ugh, I really don't like this message very much
1338
- }
1339
- return {
1340
- binding,
1341
- id: preview_id,
1342
- };
1343
- }
1344
- ),
1345
- vars: config.vars,
1346
- wasm_modules: config.wasm_modules,
1347
- text_blobs: config.text_blobs,
1348
- durable_objects: config.durable_objects,
1349
- r2_buckets: config.r2_buckets,
1350
- unsafe: config.unsafe?.bindings,
1351
- }}
1352
- inspectorPort={await getPort({ port: 9229 })}
1353
- />
1354
- );
1355
- await waitUntilExit();
1356
- }
1357
- );
1358
-
1359
- // [DEPRECATED] route
1360
- wrangler.command(
1361
- "route",
1362
- false, // I think we want to hide this command
1363
- // "➡️ List or delete worker routes",
1364
- (routeYargs) => {
1365
- return routeYargs
1366
- .command(
1367
- "list",
1368
- "List the routes associated with a zone",
1369
- (yargs) => {
1370
- return yargs
1371
- .option("env", {
1372
- type: "string",
1373
- describe: "Perform on a specific environment",
1374
- })
1375
- .option("zone", {
1376
- type: "string",
1377
- describe: "Zone id",
1378
- })
1379
- .positional("zone", {
1380
- describe: "Zone id",
1381
- type: "string",
1382
- });
1383
- },
1384
- () => {
1385
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1386
- const deprecationNotice =
1387
- "`wrangler route list` has been deprecated.";
1388
- const futureRoutes =
1389
- "Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.";
1390
- const presentRoutes =
1391
- "Refer to the Cloudflare Dashboard to see the routes this worker is currently running on.";
1392
- throw new DeprecationError(
1393
- `${deprecationNotice}\n${futureRoutes}\n${presentRoutes}`
1394
- );
1395
- }
1396
- )
1397
- .command(
1398
- "delete",
1399
- "Delete a route associated with a zone",
1400
- (yargs) => {
1401
- return yargs
1402
- .positional("id", {
1403
- describe: "The hash of the route ID to delete.",
1404
- type: "string",
1405
- })
1406
- .option("zone", {
1407
- type: "string",
1408
- describe: "zone id",
1409
- })
1410
- .option("env", {
1411
- type: "string",
1412
- describe: "Perform on a specific environment",
1413
- });
1414
- },
1415
- () => {
1416
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1417
- const deprecationNotice =
1418
- "`wrangler route delete` has been deprecated.";
1419
- const shouldDo =
1420
- "Remove the unwanted route(s) from wrangler.toml and run `wrangler publish` to remove your worker from those routes.";
1421
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1422
- }
1423
- );
1424
- },
1425
- () => {
1426
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1427
- const deprecationNotice = "`wrangler route` has been deprecated.";
1428
- const shouldDo =
1429
- "Please use wrangler.toml and/or `wrangler publish --routes` to modify routes";
1430
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1431
- }
1432
- );
1433
-
1434
- // subdomain
1435
- wrangler.command(
1436
- "subdomain [name]",
1437
- false,
1438
- // "👷 Create or change your workers.dev subdomain.",
1439
- (yargs) => {
1440
- return yargs.positional("name", { type: "string" });
1441
- },
1442
- () => {
1443
- throw new DeprecationError(
1444
- "`wrangler subdomain` has been deprecated, please refer to https://github.com/cloudflare/wrangler2/blob/main/docs/deprecations.md#subdomain for alternatives"
1445
- );
1446
- }
1447
- );
1448
-
1449
- // secret
1450
- wrangler.command(
1451
- "secret",
1452
- "🤫 Generate a secret that can be referenced in the worker script",
1453
- (secretYargs) => {
1454
- return secretYargs
1455
- .command(subHelp)
1456
- .command(
1457
- "put <key>",
1458
- "Create or update a secret variable for a script",
1459
- (yargs) => {
1460
- return yargs
1461
- .positional("key", {
1462
- describe: "The variable name to be accessible in the script",
1463
- type: "string",
1464
- })
1465
- .option("name", {
1466
- describe: "Name of the worker",
1467
- type: "string",
1468
- })
1469
- .option("env", {
1470
- type: "string",
1471
- describe:
1472
- "Binds the secret to the Worker of the specific environment",
1473
- alias: "e",
1474
- });
1475
- },
1476
- async (args) => {
1477
- printWranglerBanner();
1478
- const config = readConfig(args.config as ConfigPath, args.env);
1479
-
1480
- const scriptName = getScriptName(args, config);
1481
- if (!scriptName) {
1482
- throw new Error("Missing script name");
1483
- }
1484
-
1485
- const isInteractive = process.stdin.isTTY;
1486
- const accountId = await requireAuth(config, isInteractive);
1487
-
1488
- const secretValue = isInteractive
1489
- ? await prompt("Enter a secret value:", "password")
1490
- : await readFromStdin();
1491
-
1492
- console.log(
1493
- `🌀 Creating the secret for script ${scriptName} ${
1494
- args.env && !isLegacyEnv(args, config) ? `(${args.env})` : ""
1495
- }`
1496
- );
1497
-
1498
- async function submitSecret() {
1499
- const url =
1500
- !args.env || isLegacyEnv(args, config)
1501
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1502
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1503
-
1504
- return await fetchResult(url, {
1505
- method: "PUT",
1506
- headers: { "Content-Type": "application/json" },
1507
- body: JSON.stringify({
1508
- name: args.key,
1509
- text: secretValue,
1510
- type: "secret_text",
1511
- }),
1512
- });
1513
- }
1514
-
1515
- const createDraftWorker = async () => {
1516
- // TODO: log a warning
1517
- await fetchResult(
1518
- !args["legacy-env"] && args.env
1519
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}`
1520
- : `/accounts/${accountId}/workers/scripts/${scriptName}`,
1521
- {
1522
- method: "PUT",
1523
- body: createWorkerUploadForm({
1524
- name: scriptName,
1525
- main: {
1526
- name: scriptName,
1527
- content: `export default { fetch() {} }`,
1528
- type: "esm",
1529
- },
1530
- bindings: {
1531
- kv_namespaces: [],
1532
- vars: {},
1533
- durable_objects: { bindings: [] },
1534
- r2_buckets: [],
1535
- wasm_modules: {},
1536
- text_blobs: {},
1537
- unsafe: [],
1538
- },
1539
- modules: [],
1540
- migrations: undefined,
1541
- compatibility_date: undefined,
1542
- compatibility_flags: undefined,
1543
- usage_model: undefined,
1544
- }),
1545
- }
1546
- );
1547
- };
1548
-
1549
- function isMissingWorkerError(e: unknown): e is { code: 10007 } {
1550
- return (
1551
- typeof e === "object" &&
1552
- e !== null &&
1553
- (e as { code: 10007 }).code === 10007
1554
- );
1555
- }
1556
-
1557
- try {
1558
- await submitSecret();
1559
- } catch (e) {
1560
- if (isMissingWorkerError(e)) {
1561
- // create a draft worker and try again
1562
- await createDraftWorker();
1563
- await submitSecret();
1564
- // TODO: delete the draft worker if this failed too?
1565
- } else {
1566
- throw e;
1567
- }
1568
- }
1569
-
1570
- console.log(`✨ Success! Uploaded secret ${args.key}`);
1571
- }
1572
- )
1573
- .command(
1574
- "delete <key>",
1575
- "Delete a secret variable from a script",
1576
- (yargs) => {
1577
- printWranglerBanner();
1578
- return yargs
1579
- .positional("key", {
1580
- describe: "The variable name to be accessible in the script",
1581
- type: "string",
1582
- })
1583
- .option("name", {
1584
- describe: "Name of the worker",
1585
- type: "string",
1586
- })
1587
- .option("env", {
1588
- type: "string",
1589
- describe:
1590
- "Binds the secret to the Worker of the specific environment",
1591
- alias: "e",
1592
- });
1593
- },
1594
- async (args) => {
1595
- const config = readConfig(args.config as ConfigPath, args.env);
1596
-
1597
- const scriptName = getScriptName(args, config);
1598
- if (!scriptName) {
1599
- throw new Error("Missing script name");
1600
- }
1601
-
1602
- const accountId = await requireAuth(config);
1603
-
1604
- if (
1605
- await confirm(
1606
- `Are you sure you want to permanently delete the variable ${
1607
- args.key
1608
- } on the script ${scriptName}${
1609
- args.env && !isLegacyEnv(args, config) ? ` (${args.env})` : ""
1610
- }?`
1611
- )
1612
- ) {
1613
- console.log(
1614
- `🌀 Deleting the secret ${args.key} on script ${scriptName}${
1615
- args.env && !isLegacyEnv(args, config) ? ` (${args.env})` : ""
1616
- }`
1617
- );
1618
-
1619
- const url =
1620
- !args.env || isLegacyEnv(args, config)
1621
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1622
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1623
-
1624
- await fetchResult(`${url}/${args.key}`, { method: "DELETE" });
1625
- console.log(`✨ Success! Deleted secret ${args.key}`);
1626
- }
1627
- }
1628
- )
1629
- .command(
1630
- "list",
1631
- "List all secrets for a script",
1632
- (yargs) => {
1633
- return yargs
1634
- .option("name", {
1635
- describe: "Name of the worker",
1636
- type: "string",
1637
- })
1638
- .option("env", {
1639
- type: "string",
1640
- describe:
1641
- "Binds the secret to the Worker of the specific environment.",
1642
- alias: "e",
1643
- });
1644
- },
1645
- async (args) => {
1646
- const config = readConfig(args.config as ConfigPath, args.env);
1647
-
1648
- const scriptName = getScriptName(args, config);
1649
- if (!scriptName) {
1650
- throw new Error("Missing script name");
1651
- }
1652
-
1653
- const accountId = await requireAuth(config);
1654
-
1655
- const url =
1656
- !args.env || isLegacyEnv(args, config)
1657
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1658
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1659
-
1660
- console.log(JSON.stringify(await fetchResult(url), null, " "));
1661
- }
1662
- );
1663
- }
1664
- );
1665
-
1666
- // kv
1667
- // :namespace
1668
- wrangler.command(
1669
- "kv:namespace",
1670
- "🗂️ Interact with your Workers KV Namespaces",
1671
- (namespaceYargs) => {
1672
- return namespaceYargs
1673
- .command(subHelp)
1674
- .command(
1675
- "create <namespace>",
1676
- "Create a new namespace",
1677
- (yargs) => {
1678
- return yargs
1679
- .positional("namespace", {
1680
- describe: "The name of the new namespace",
1681
- type: "string",
1682
- demandOption: true,
1683
- })
1684
- .option("env", {
1685
- type: "string",
1686
- describe: "Perform on a specific environment",
1687
- alias: "e",
1688
- })
1689
- .option("preview", {
1690
- type: "boolean",
1691
- describe: "Interact with a preview namespace",
1692
- });
1693
- },
1694
- async (args) => {
1695
- printWranglerBanner();
1696
- if (args._.length > 2) {
1697
- const extraArgs = args._.slice(2).join(" ");
1698
- throw new CommandLineArgsError(
1699
- `Unexpected additional positional arguments "${extraArgs}".`
1700
- );
1701
- }
1702
-
1703
- if (!isValidNamespaceBinding(args.namespace)) {
1704
- throw new CommandLineArgsError(
1705
- `The namespace binding name "${args.namespace}" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.`
1706
- );
1707
- }
1708
-
1709
- const config = readConfig(args.config as ConfigPath, args.env);
1710
- if (!config.name) {
1711
- console.warn(
1712
- "No configured name present, using `worker` as a prefix for the title"
1713
- );
1714
- }
1715
-
1716
- const name = config.name || "worker";
1717
- const environment = args.env ? `-${args.env}` : "";
1718
- const preview = args.preview ? "_preview" : "";
1719
- const title = `${name}${environment}-${args.namespace}${preview}`;
1720
-
1721
- const accountId = await requireAuth(config);
1722
-
1723
- // TODO: generate a binding name stripping non alphanumeric chars
1724
-
1725
- console.log(`🌀 Creating namespace with title "${title}"`);
1726
- const namespaceId = await createNamespace(accountId, title);
1727
-
1728
- console.log("✨ Success!");
1729
- const envString = args.env ? ` under [env.${args.env}]` : "";
1730
- const previewString = args.preview ? "preview_" : "";
1731
- console.log(
1732
- `Add the following to your configuration file in your kv_namespaces array${envString}:`
1733
- );
1734
- console.log(
1735
- `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
1736
- );
1737
-
1738
- // TODO: automatically write this block to the wrangler.toml config file??
1739
- }
1740
- )
1741
- .command(
1742
- "list",
1743
- "Outputs a list of all KV namespaces associated with your account id.",
1744
- {},
1745
- async (args) => {
1746
- const config = readConfig(args.config as ConfigPath, undefined);
1747
-
1748
- const accountId = await requireAuth(config);
1749
-
1750
- // TODO: we should show bindings if they exist for given ids
1751
-
1752
- console.log(
1753
- JSON.stringify(await listNamespaces(accountId), null, " ")
1754
- );
1755
- }
1756
- )
1757
- .command(
1758
- "delete",
1759
- "Deletes a given namespace.",
1760
- (yargs) => {
1761
- return yargs
1762
- .option("binding", {
1763
- type: "string",
1764
- describe: "The name of the namespace to delete",
1765
- })
1766
- .option("namespace-id", {
1767
- type: "string",
1768
- describe: "The id of the namespace to delete",
1769
- })
1770
- .check(demandOneOfOption("binding", "namespace-id"))
1771
- .option("env", {
1772
- type: "string",
1773
- describe: "Perform on a specific environment",
1774
- alias: "e",
1775
- })
1776
- .option("preview", {
1777
- type: "boolean",
1778
- describe: "Interact with a preview namespace",
1779
- });
1780
- },
1781
- async (args) => {
1782
- printWranglerBanner();
1783
- const config = readConfig(args.config as ConfigPath, args.env);
1784
-
1785
- let id;
1786
- try {
1787
- id = getNamespaceId(args, config);
1788
- } catch (e) {
1789
- throw new CommandLineArgsError(
1790
- "Not able to delete namespace.\n" + ((e as Error).message ?? e)
1791
- );
1792
- }
1793
-
1794
- const accountId = await requireAuth(config);
1795
-
1796
- await fetchResult<{ id: string }>(
1797
- `/accounts/${accountId}/storage/kv/namespaces/${id}`,
1798
- { method: "DELETE" }
1799
- );
1800
-
1801
- // TODO: recommend they remove it from wrangler.toml
1802
-
1803
- // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1804
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1805
- // n
1806
- // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1807
- // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1808
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1809
- // y
1810
- // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1811
- // ✨ Success
1812
- // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
1813
- // ➜ test-mf
1814
-
1815
- // TODO: do it automatically
1816
-
1817
- // TODO: delete the preview namespace as well?
1818
- }
1819
- );
1820
- }
1821
- );
1822
-
1823
- // :key
1824
- wrangler.command(
1825
- "kv:key",
1826
- "🔑 Individually manage Workers KV key-value pairs",
1827
- (kvKeyYargs) => {
1828
- return kvKeyYargs
1829
- .command(subHelp)
1830
- .command(
1831
- "put <key> [value]",
1832
- "Writes a single key/value pair to the given namespace.",
1833
- (yargs) => {
1834
- return yargs
1835
- .positional("key", {
1836
- type: "string",
1837
- describe: "The key to write to",
1838
- demandOption: true,
1839
- })
1840
- .positional("value", {
1841
- type: "string",
1842
- describe: "The value to write",
1843
- })
1844
- .option("binding", {
1845
- type: "string",
1846
- describe: "The binding of the namespace to write to",
1847
- })
1848
- .option("namespace-id", {
1849
- type: "string",
1850
- describe: "The id of the namespace to write to",
1851
- })
1852
- .check(demandOneOfOption("binding", "namespace-id"))
1853
- .option("env", {
1854
- type: "string",
1855
- describe: "Perform on a specific environment",
1856
- alias: "e",
1857
- })
1858
- .option("preview", {
1859
- type: "boolean",
1860
- describe: "Interact with a preview namespace",
1861
- })
1862
- .option("ttl", {
1863
- type: "number",
1864
- describe: "Time for which the entries should be visible",
1865
- })
1866
- .option("expiration", {
1867
- type: "number",
1868
- describe:
1869
- "Time since the UNIX epoch after which the entry expires",
1870
- })
1871
- .option("path", {
1872
- type: "string",
1873
- describe: "Read value from the file at a given path",
1874
- })
1875
- .check(demandOneOfOption("value", "path"));
1876
- },
1877
- async ({ key, ttl, expiration, ...args }) => {
1878
- printWranglerBanner();
1879
- const config = readConfig(args.config as ConfigPath, args.env);
1880
- const namespaceId = getNamespaceId(args, config);
1881
- // One of `args.path` and `args.value` must be defined
1882
- const value = args.path
1883
- ? readFileSync(args.path)
1884
- : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1885
- args.value!;
1886
-
1887
- if (args.path) {
1888
- console.log(
1889
- `writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}`
1890
- );
1891
- } else {
1892
- console.log(
1893
- `writing the value "${value}" to key "${key}" on namespace ${namespaceId}`
1894
- );
1895
- }
1896
-
1897
- const accountId = await requireAuth(config);
1898
-
1899
- await putKeyValue(accountId, namespaceId, {
1900
- key,
1901
- value,
1902
- expiration,
1903
- expiration_ttl: ttl,
1904
- });
1905
- }
1906
- )
1907
- .command(
1908
- "list",
1909
- "Outputs a list of all keys in a given namespace.",
1910
- (yargs) => {
1911
- return yargs
1912
- .option("binding", {
1913
- type: "string",
1914
- describe: "The name of the namespace to list",
1915
- })
1916
- .option("namespace-id", {
1917
- type: "string",
1918
- describe: "The id of the namespace to list",
1919
- })
1920
- .check(demandOneOfOption("binding", "namespace-id"))
1921
- .option("env", {
1922
- type: "string",
1923
- describe: "Perform on a specific environment",
1924
- alias: "e",
1925
- })
1926
- .option("preview", {
1927
- type: "boolean",
1928
- // In the case of listing keys we will default to non-preview mode
1929
- default: false,
1930
- describe: "Interact with a preview namespace",
1931
- })
1932
- .option("prefix", {
1933
- type: "string",
1934
- describe: "A prefix to filter listed keys",
1935
- });
1936
- },
1937
- async ({ prefix, ...args }) => {
1938
- // TODO: support for limit+cursor (pagination)
1939
- const config = readConfig(args.config as ConfigPath, args.env);
1940
- const namespaceId = getNamespaceId(args, config);
1941
-
1942
- const accountId = await requireAuth(config);
1943
-
1944
- const results = await listNamespaceKeys(
1945
- accountId,
1946
- namespaceId,
1947
- prefix
1948
- );
1949
- console.log(JSON.stringify(results, undefined, 2));
1950
- }
1951
- )
1952
- .command(
1953
- "get <key>",
1954
- "Reads a single value by key from the given namespace.",
1955
- (yargs) => {
1956
- return yargs
1957
- .positional("key", {
1958
- describe: "The key value to get.",
1959
- type: "string",
1960
- demandOption: true,
1961
- })
1962
- .option("binding", {
1963
- type: "string",
1964
- describe: "The name of the namespace to get from",
1965
- })
1966
- .option("namespace-id", {
1967
- type: "string",
1968
- describe: "The id of the namespace to get from",
1969
- })
1970
- .check(demandOneOfOption("binding", "namespace-id"))
1971
- .option("env", {
1972
- type: "string",
1973
- describe: "Perform on a specific environment",
1974
- alias: "e",
1975
- })
1976
- .option("preview", {
1977
- type: "boolean",
1978
- describe: "Interact with a preview namespace",
1979
- })
1980
- .option("preview", {
1981
- type: "boolean",
1982
- // In the case of getting key values we will default to non-preview mode
1983
- default: false,
1984
- describe: "Interact with a preview namespace",
1985
- });
1986
- },
1987
- async ({ key, ...args }) => {
1988
- const config = readConfig(args.config as ConfigPath, args.env);
1989
- const namespaceId = getNamespaceId(args, config);
1990
-
1991
- const accountId = await requireAuth(config);
1992
-
1993
- console.log(await getKeyValue(accountId, namespaceId, key));
1994
- }
1995
- )
1996
- .command(
1997
- "delete <key>",
1998
- "Removes a single key value pair from the given namespace.",
1999
- (yargs) => {
2000
- return yargs
2001
- .positional("key", {
2002
- describe: "The key value to delete",
2003
- type: "string",
2004
- demandOption: true,
2005
- })
2006
- .option("binding", {
2007
- type: "string",
2008
- describe: "The name of the namespace to delete from",
2009
- })
2010
- .option("namespace-id", {
2011
- type: "string",
2012
- describe: "The id of the namespace to delete from",
2013
- })
2014
- .check(demandOneOfOption("binding", "namespace-id"))
2015
- .option("env", {
2016
- type: "string",
2017
- describe: "Perform on a specific environment",
2018
- alias: "e",
2019
- })
2020
- .option("preview", {
2021
- type: "boolean",
2022
- describe: "Interact with a preview namespace",
2023
- });
2024
- },
2025
- async ({ key, ...args }) => {
2026
- printWranglerBanner();
2027
- const config = readConfig(args.config as ConfigPath, args.env);
2028
- const namespaceId = getNamespaceId(args, config);
2029
-
2030
- console.log(
2031
- `deleting the key "${key}" on namespace ${namespaceId}`
2032
- );
2033
-
2034
- const accountId = await requireAuth(config);
2035
-
2036
- await fetchResult(
2037
- `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`,
2038
- { method: "DELETE" }
2039
- );
2040
- }
2041
- );
2042
- }
2043
- );
2044
-
2045
- // :bulk
2046
- wrangler.command(
2047
- "kv:bulk",
2048
- "💪 Interact with multiple Workers KV key-value pairs at once",
2049
- (kvBulkYargs) => {
2050
- return kvBulkYargs
2051
- .command(subHelp)
2052
- .command(
2053
- "put <filename>",
2054
- "Upload multiple key-value pairs to a namespace",
2055
- (yargs) => {
2056
- return yargs
2057
- .positional("filename", {
2058
- describe: `The JSON file of key-value pairs to upload, in form [{"key":..., "value":...}"...]`,
2059
- type: "string",
2060
- demandOption: true,
2061
- })
2062
- .option("binding", {
2063
- type: "string",
2064
- describe: "The name of the namespace to insert values into",
2065
- })
2066
- .option("namespace-id", {
2067
- type: "string",
2068
- describe: "The id of the namespace to insert values into",
2069
- })
2070
- .check(demandOneOfOption("binding", "namespace-id"))
2071
- .option("env", {
2072
- type: "string",
2073
- describe: "Perform on a specific environment",
2074
- alias: "e",
2075
- })
2076
- .option("preview", {
2077
- type: "boolean",
2078
- describe: "Interact with a preview namespace",
2079
- });
2080
- },
2081
- async ({ filename, ...args }) => {
2082
- printWranglerBanner();
2083
- // The simplest implementation I could think of.
2084
- // This could be made more efficient with a streaming parser/uploader
2085
- // but we'll do that in the future if needed.
2086
-
2087
- const config = readConfig(args.config as ConfigPath, args.env);
2088
- const namespaceId = getNamespaceId(args, config);
2089
- const content = parseJSON(readFileSync(filename), filename);
2090
-
2091
- if (!Array.isArray(content)) {
2092
- throw new Error(
2093
- `Unexpected JSON input from "${filename}".\n` +
2094
- `Expected an array of key-value objects but got type "${typeof content}".`
2095
- );
2096
- }
2097
-
2098
- const errors: string[] = [];
2099
- const warnings: string[] = [];
2100
- for (let i = 0; i < content.length; i++) {
2101
- const keyValue = content[i];
2102
- if (typeof keyValue !== "object") {
2103
- errors.push(
2104
- `The item at index ${i} is type: "${typeof keyValue}" - ${JSON.stringify(
2105
- keyValue
2106
- )}`
2107
- );
2108
- } else if (!isKeyValue(keyValue)) {
2109
- errors.push(
2110
- `The item at index ${i} is ${JSON.stringify(keyValue)}`
2111
- );
2112
- } else {
2113
- const props = unexpectedKeyValueProps(keyValue);
2114
- if (props.length > 0) {
2115
- warnings.push(
2116
- `The item at index ${i} contains unexpected properties: ${JSON.stringify(
2117
- props
2118
- )}.`
2119
- );
2120
- }
2121
- }
2122
- }
2123
- if (warnings.length > 0) {
2124
- console.warn(
2125
- `Unexpected key-value properties in "${filename}".\n` +
2126
- warnings.join("\n")
2127
- );
2128
- }
2129
- if (errors.length > 0) {
2130
- throw new Error(
2131
- `Unexpected JSON input from "${filename}".\n` +
2132
- `Each item in the array should be an object that matches:\n\n` +
2133
- `interface KeyValue {\n` +
2134
- ` key: string;\n` +
2135
- ` value: string;\n` +
2136
- ` expiration?: number;\n` +
2137
- ` expiration_ttl?: number;\n` +
2138
- ` metadata?: object;\n` +
2139
- ` base64?: boolean;\n` +
2140
- `}\n\n` +
2141
- errors.join("\n")
2142
- );
2143
- }
2144
-
2145
- const accountId = await requireAuth(config);
2146
- await putBulkKeyValue(
2147
- accountId,
2148
- namespaceId,
2149
- content,
2150
- (index, total) => {
2151
- console.log(`Uploaded ${index} of ${total}.`);
2152
- }
2153
- );
2154
-
2155
- console.log("Success!");
2156
- }
2157
- )
2158
- .command(
2159
- "delete <filename>",
2160
- "Delete multiple key-value pairs from a namespace",
2161
- (yargs) => {
2162
- return yargs
2163
- .positional("filename", {
2164
- describe: `The JSON file of keys to delete, in the form ["key1", "key2", ...]`,
2165
- type: "string",
2166
- demandOption: true,
2167
- })
2168
- .option("binding", {
2169
- type: "string",
2170
- describe: "The name of the namespace to delete from",
2171
- })
2172
- .option("namespace-id", {
2173
- type: "string",
2174
- describe: "The id of the namespace to delete from",
2175
- })
2176
- .check(demandOneOfOption("binding", "namespace-id"))
2177
- .option("env", {
2178
- type: "string",
2179
- describe: "Perform on a specific environment",
2180
- alias: "e",
2181
- })
2182
- .option("preview", {
2183
- type: "boolean",
2184
- describe: "Interact with a preview namespace",
2185
- })
2186
- .option("force", {
2187
- type: "boolean",
2188
- alias: "f",
2189
- describe: "Do not ask for confirmation before deleting",
2190
- });
2191
- },
2192
- async ({ filename, ...args }) => {
2193
- printWranglerBanner();
2194
- const config = readConfig(args.config as ConfigPath, args.env);
2195
- const namespaceId = getNamespaceId(args, config);
2196
-
2197
- if (!args.force) {
2198
- const result = await confirm(
2199
- `Are you sure you want to delete all the keys read from "${filename}" from kv-namespace with id "${namespaceId}"?`
2200
- );
2201
- if (!result) {
2202
- console.log(`Not deleting keys read from "${filename}".`);
2203
- return;
2204
- }
2205
- }
2206
-
2207
- const content = parseJSON(
2208
- readFileSync(filename),
2209
- filename
2210
- ) as string[];
2211
-
2212
- if (!Array.isArray(content)) {
2213
- throw new Error(
2214
- `Unexpected JSON input from "${filename}".\n` +
2215
- `Expected an array of strings but got:\n${content}`
2216
- );
2217
- }
2218
-
2219
- const errors: string[] = [];
2220
- for (let i = 0; i < content.length; i++) {
2221
- const key = content[i];
2222
- if (typeof key !== "string") {
2223
- errors.push(
2224
- `The item at index ${i} is type: "${typeof key}" - ${JSON.stringify(
2225
- key
2226
- )}`
2227
- );
2228
- }
2229
- }
2230
- if (errors.length > 0) {
2231
- throw new Error(
2232
- `Unexpected JSON input from "${filename}".\n` +
2233
- `Expected an array of strings.\n` +
2234
- errors.join("\n")
2235
- );
2236
- }
2237
-
2238
- const accountId = await requireAuth(config);
2239
-
2240
- await deleteBulkKeyValue(
2241
- accountId,
2242
- namespaceId,
2243
- content,
2244
- (index, total) => {
2245
- console.log(`Deleted ${index} of ${total}.`);
2246
- }
2247
- );
2248
-
2249
- console.log("Success!");
2250
- }
2251
- );
2252
- }
2253
- );
2254
-
2255
- wrangler.command("pages", "⚡️ Configure Cloudflare Pages", (pagesYargs) =>
2256
- pages(pagesYargs.command(subHelp))
2257
- );
2258
-
2259
- wrangler.command("r2", "📦 Interact with an R2 store", (r2Yargs) => {
2260
- return r2Yargs
2261
- .command(subHelp)
2262
- .command("bucket", "Manage R2 buckets", (r2BucketYargs) => {
2263
- r2BucketYargs.command(
2264
- "create <name>",
2265
- "Create a new R2 bucket",
2266
- (yargs) => {
2267
- return yargs.positional("name", {
2268
- describe: "The name of the new bucket",
2269
- type: "string",
2270
- demandOption: true,
2271
- });
2272
- },
2273
- async (args) => {
2274
- printWranglerBanner();
2275
- // We expect three values in `_`: `r2`, `bucket`, `create`.
2276
- if (args._.length > 3) {
2277
- const extraArgs = args._.slice(3).join(" ");
2278
- throw new CommandLineArgsError(
2279
- `Unexpected additional positional arguments "${extraArgs}".`
2280
- );
2281
- }
2282
-
2283
- const config = readConfig(args.config as ConfigPath, undefined);
2284
-
2285
- const accountId = await requireAuth(config);
2286
-
2287
- console.log(`Creating bucket ${args.name}.`);
2288
- await createR2Bucket(accountId, args.name);
2289
- console.log(`Created bucket ${args.name}.`);
2290
- }
2291
- );
2292
-
2293
- r2BucketYargs.command("list", "List R2 buckets", {}, async (args) => {
2294
- const config = readConfig(args.config as ConfigPath, undefined);
2295
-
2296
- const accountId = await requireAuth(config);
2297
-
2298
- console.log(JSON.stringify(await listR2Buckets(accountId), null, 2));
2299
- });
2300
-
2301
- r2BucketYargs.command(
2302
- "delete <name>",
2303
- "Delete an R2 bucket",
2304
- (yargs) => {
2305
- return yargs.positional("name", {
2306
- describe: "The name of the bucket to delete",
2307
- type: "string",
2308
- demandOption: true,
2309
- });
2310
- },
2311
- async (args) => {
2312
- printWranglerBanner();
2313
- // We expect three values in `_`: `r2`, `bucket`, `delete`.
2314
- if (args._.length > 3) {
2315
- const extraArgs = args._.slice(3).join(" ");
2316
- throw new CommandLineArgsError(
2317
- `Unexpected additional positional arguments "${extraArgs}".`
2318
- );
2319
- }
2320
-
2321
- const config = readConfig(args.config as ConfigPath, undefined);
2322
-
2323
- const accountId = await requireAuth(config);
2324
-
2325
- console.log(`Deleting bucket ${args.name}.`);
2326
- await deleteR2Bucket(accountId, args.name);
2327
- console.log(`Deleted bucket ${args.name}.`);
2328
- }
2329
- );
2330
- return r2BucketYargs;
2331
- });
2332
- });
2333
-
2334
- wrangler
2335
- .option("legacy-env", {
2336
- type: "boolean",
2337
- describe: "Use legacy environments",
2338
- })
2339
- .option("config", {
2340
- alias: "c",
2341
- describe: "Path to .toml configuration file",
2342
- type: "string",
2343
- });
2344
-
2345
- wrangler.group(["config", "help", "version", "legacy-env"], "Flags:");
2346
- wrangler.help().alias("h", "help");
2347
- wrangler.version(wranglerVersion).alias("v", "version");
2348
- wrangler.exitProcess(false);
2349
-
2350
- try {
2351
- await wrangler.parse();
2352
- } catch (e) {
2353
- if (e instanceof CommandLineArgsError) {
2354
- wrangler.showHelp("error");
2355
- console.error(""); // Just adds a bit of space
2356
- console.error(e.message);
2357
- } else if (e instanceof ParseError) {
2358
- console.error("");
2359
- e.notes.push({
2360
- text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/wrangler2/issues/new",
2361
- });
2362
- console.error(formatMessage(e));
2363
- } else {
2364
- console.error(e instanceof Error ? e.message : e);
2365
- console.error(""); // Just adds a bit of space
2366
- console.error(
2367
- `${fgGreenColor}%s${resetColor}`,
2368
- "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
2369
- );
2370
- }
2371
- throw e;
2372
- }
2373
- }