wrangler 0.0.0-e6733a3 → 0.0.0-e9307365

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 (220) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +159 -27
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5416 -0
  6. package/package.json +171 -124
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +4022 -0
  10. package/src/__tests__/dev.test.tsx +1290 -62
  11. package/src/__tests__/generate.test.ts +93 -0
  12. package/src/__tests__/guess-worker-format.test.ts +85 -0
  13. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  14. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  15. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  16. package/src/__tests__/helpers/mock-bin.ts +36 -0
  17. package/src/__tests__/helpers/mock-cfetch.ts +263 -0
  18. package/src/__tests__/helpers/mock-console.ts +97 -0
  19. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-kv.ts +33 -0
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  24. package/src/__tests__/helpers/mock-process.ts +39 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  30. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  31. package/src/__tests__/https-options.test.ts +163 -0
  32. package/src/__tests__/index.test.ts +242 -284
  33. package/src/__tests__/init.test.ts +1992 -0
  34. package/src/__tests__/jest.setup.ts +138 -10
  35. package/src/__tests__/kv.test.ts +1459 -886
  36. package/src/__tests__/logger.test.ts +141 -0
  37. package/src/__tests__/metrics.test.ts +450 -0
  38. package/src/__tests__/package-manager.test.ts +353 -0
  39. package/src/__tests__/pages.test.ts +1261 -0
  40. package/src/__tests__/parse.test.ts +330 -0
  41. package/src/__tests__/publish.test.ts +6914 -0
  42. package/src/__tests__/pubsub.test.ts +367 -0
  43. package/src/__tests__/r2.test.ts +317 -0
  44. package/src/__tests__/route.test.ts +45 -0
  45. package/src/__tests__/secret.test.ts +492 -0
  46. package/src/__tests__/tail.test.ts +698 -0
  47. package/src/__tests__/test-old-node-version.js +31 -0
  48. package/src/__tests__/user.test.ts +144 -0
  49. package/src/__tests__/validate-dev-props.test.ts +56 -0
  50. package/src/__tests__/version.test.ts +35 -0
  51. package/src/__tests__/whoami.test.tsx +289 -0
  52. package/src/__tests__/worker-namespace.test.ts +327 -0
  53. package/src/abort.d.ts +3 -0
  54. package/src/api/dev.ts +86 -0
  55. package/src/api/index.ts +1 -0
  56. package/src/bundle-reporter.tsx +29 -0
  57. package/src/bundle.ts +472 -0
  58. package/src/cfetch/index.ts +88 -69
  59. package/src/cfetch/internal.ts +156 -44
  60. package/src/cli.ts +24 -6
  61. package/src/config/README.md +107 -0
  62. package/src/config/config.ts +263 -0
  63. package/src/config/diagnostics.ts +80 -0
  64. package/src/config/environment.ts +485 -0
  65. package/src/config/index.ts +251 -0
  66. package/src/config/validation-helpers.ts +584 -0
  67. package/src/config/validation.ts +1856 -0
  68. package/src/config-cache.ts +84 -0
  69. package/src/create-worker-preview.ts +257 -0
  70. package/src/create-worker-upload-form.ts +288 -0
  71. package/src/dev/dev-vars.ts +36 -0
  72. package/src/dev/dev.tsx +531 -0
  73. package/src/dev/local.tsx +385 -0
  74. package/src/dev/remote.tsx +413 -0
  75. package/src/dev/use-esbuild.ts +175 -0
  76. package/src/dev/validate-dev-props.ts +31 -0
  77. package/src/dev-registry.tsx +157 -0
  78. package/src/dev.tsx +603 -758
  79. package/src/dialogs.tsx +117 -59
  80. package/src/durable.ts +102 -0
  81. package/src/entry.ts +328 -0
  82. package/src/environment-variables.ts +35 -0
  83. package/src/errors.ts +11 -0
  84. package/src/faye-websocket.d.ts +6 -0
  85. package/src/generate.ts +131 -0
  86. package/src/git-client.ts +42 -0
  87. package/src/global-wrangler-config-path.ts +26 -0
  88. package/src/https-options.ts +127 -0
  89. package/src/index.tsx +2166 -1956
  90. package/src/init.ts +549 -0
  91. package/src/inspect.ts +703 -477
  92. package/src/intl-polyfill.d.ts +139 -0
  93. package/src/is-interactive.ts +12 -0
  94. package/src/kv.ts +430 -0
  95. package/src/logger.ts +73 -0
  96. package/src/metrics/index.ts +5 -0
  97. package/src/metrics/is-ci.ts +14 -0
  98. package/src/metrics/metrics-config.ts +239 -0
  99. package/src/metrics/metrics-dispatcher.ts +96 -0
  100. package/src/metrics/metrics-usage-headers.ts +24 -0
  101. package/src/metrics/send-event.ts +92 -0
  102. package/src/miniflare-cli/README.md +30 -0
  103. package/src/miniflare-cli/assets.ts +543 -0
  104. package/src/miniflare-cli/enum-keys.ts +17 -0
  105. package/src/miniflare-cli/index.ts +85 -0
  106. package/src/miniflare-cli/request-context.ts +40 -0
  107. package/src/module-collection.ts +247 -53
  108. package/src/open-in-browser.ts +17 -0
  109. package/src/package-manager.ts +219 -0
  110. package/src/pages/build.tsx +204 -0
  111. package/src/pages/constants.ts +8 -0
  112. package/src/pages/deployments.tsx +106 -0
  113. package/src/pages/dev.tsx +414 -0
  114. package/src/pages/functions/buildPlugin.ts +105 -0
  115. package/src/pages/functions/buildWorker.ts +151 -0
  116. package/src/pages/functions/filepath-routing.test.ts +234 -0
  117. package/src/pages/functions/filepath-routing.ts +189 -0
  118. package/src/pages/functions/identifiers.ts +78 -0
  119. package/src/pages/functions/routes.ts +151 -0
  120. package/src/pages/index.tsx +84 -0
  121. package/src/pages/projects.tsx +163 -0
  122. package/src/pages/publish.tsx +338 -0
  123. package/src/pages/types.ts +40 -0
  124. package/src/pages/upload.tsx +415 -0
  125. package/src/pages/utils.ts +12 -0
  126. package/src/parse.ts +286 -0
  127. package/src/paths.ts +26 -0
  128. package/src/preview.ts +31 -0
  129. package/src/proxy.ts +434 -252
  130. package/src/publish.ts +794 -345
  131. package/src/pubsub/index.ts +286 -0
  132. package/src/pubsub/pubsub-commands.tsx +623 -0
  133. package/src/r2.ts +118 -0
  134. package/src/selfsigned.d.ts +29 -0
  135. package/src/sites.tsx +357 -99
  136. package/src/tail/filters.ts +279 -0
  137. package/src/tail/index.ts +299 -0
  138. package/src/tail/printing.ts +67 -0
  139. package/src/update-check.ts +19 -0
  140. package/src/user/choose-account.tsx +69 -0
  141. package/src/user/env-vars.ts +46 -0
  142. package/src/user/generate-auth-url.ts +33 -0
  143. package/src/user/generate-random-state.ts +16 -0
  144. package/src/user/index.ts +3 -0
  145. package/src/user/user.tsx +1189 -0
  146. package/src/whoami.tsx +169 -0
  147. package/src/worker-namespace.ts +206 -0
  148. package/src/worker.ts +203 -0
  149. package/src/zones.ts +76 -0
  150. package/templates/checked-fetch.js +17 -0
  151. package/templates/first-party-worker-module-facade.ts +18 -0
  152. package/templates/format-dev-errors.ts +32 -0
  153. package/templates/gitignore +171 -0
  154. package/templates/new-worker-scheduled.js +17 -0
  155. package/templates/new-worker-scheduled.ts +32 -0
  156. package/templates/new-worker.js +15 -0
  157. package/templates/new-worker.ts +30 -0
  158. package/templates/no-op-worker.js +10 -0
  159. package/templates/pages-shim.ts +9 -0
  160. package/templates/pages-template-plugin.ts +155 -0
  161. package/templates/pages-template-worker.ts +161 -0
  162. package/templates/serve-static-assets.ts +63 -0
  163. package/templates/service-bindings-module-facade.js +51 -0
  164. package/templates/service-bindings-sw-facade.js +39 -0
  165. package/templates/tsconfig.json +105 -0
  166. package/wrangler-dist/cli.d.ts +327 -0
  167. package/wrangler-dist/cli.js +134880 -109997
  168. package/pages/functions/buildWorker.ts +0 -62
  169. package/pages/functions/filepath-routing.test.ts +0 -39
  170. package/pages/functions/filepath-routing.ts +0 -221
  171. package/pages/functions/identifiers.ts +0 -78
  172. package/pages/functions/routes.ts +0 -158
  173. package/pages/functions/template-worker.ts +0 -144
  174. package/src/__tests__/mock-cfetch.ts +0 -171
  175. package/src/__tests__/mock-dialogs.ts +0 -65
  176. package/src/__tests__/run-in-tmp.ts +0 -19
  177. package/src/__tests__/run-wrangler.ts +0 -32
  178. package/src/api/form_data.ts +0 -131
  179. package/src/api/preview.ts +0 -128
  180. package/src/api/worker.ts +0 -155
  181. package/src/config.ts +0 -487
  182. package/src/kv.tsx +0 -267
  183. package/src/pages.tsx +0 -1031
  184. package/src/tail.tsx +0 -73
  185. package/src/user.tsx +0 -1025
  186. package/static-asset-facade.js +0 -47
  187. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  188. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  189. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  190. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  191. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  192. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  193. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  194. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  195. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  196. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  201. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  202. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  203. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  204. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  205. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  206. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  207. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  209. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  210. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  211. package/vendor/wrangler-mime/LICENSE +0 -21
  212. package/vendor/wrangler-mime/Mime.js +0 -97
  213. package/vendor/wrangler-mime/README.md +0 -187
  214. package/vendor/wrangler-mime/cli.js +0 -46
  215. package/vendor/wrangler-mime/index.js +0 -4
  216. package/vendor/wrangler-mime/lite.js +0 -4
  217. package/vendor/wrangler-mime/package.json +0 -52
  218. package/vendor/wrangler-mime/types/other.js +0 -1
  219. package/vendor/wrangler-mime/types/standard.js +0 -1
  220. package/wrangler-dist/cli.js.map +0 -7
package/src/init.ts ADDED
@@ -0,0 +1,549 @@
1
+ import * as fs from "node:fs";
2
+ import { writeFile, mkdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import TOML from "@iarna/toml";
5
+ import { findUp } from "find-up";
6
+ import { version as wranglerVersion } from "../package.json";
7
+
8
+ import { confirm, select } from "./dialogs";
9
+ import { initializeGit, isGitInstalled, isInsideGitRepo } from "./git-client";
10
+ import { logger } from "./logger";
11
+ import { getPackageManager } from "./package-manager";
12
+ import { parsePackageJSON, parseTOML, readFileSync } from "./parse";
13
+ import { CommandLineArgsError, printWranglerBanner } from "./index";
14
+
15
+ import type { Argv, ArgumentsCamelCase } from "yargs";
16
+
17
+ export async function initOptions(yargs: Argv) {
18
+ return yargs
19
+ .positional("name", {
20
+ describe: "The name of your worker",
21
+ type: "string",
22
+ })
23
+ .option("type", {
24
+ describe: "The type of worker to create",
25
+ type: "string",
26
+ choices: ["rust", "javascript", "webpack"],
27
+ hidden: true,
28
+ deprecated: true,
29
+ })
30
+ .option("site", {
31
+ hidden: true,
32
+ type: "boolean",
33
+ deprecated: true,
34
+ })
35
+ .option("yes", {
36
+ describe: 'Answer "yes" to any prompts for new projects',
37
+ type: "boolean",
38
+ alias: "y",
39
+ });
40
+ }
41
+
42
+ interface InitArgs {
43
+ name: string;
44
+ type?: string;
45
+ site?: boolean;
46
+ yes?: boolean;
47
+ }
48
+
49
+ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
50
+ await printWranglerBanner();
51
+ if (args.type) {
52
+ let message = "The --type option is no longer supported.";
53
+ if (args.type === "webpack") {
54
+ message +=
55
+ "\nIf you wish to use webpack then you will need to create a custom build.";
56
+ // TODO: Add a link to docs
57
+ }
58
+ throw new CommandLineArgsError(message);
59
+ }
60
+
61
+ const devDepsToInstall: string[] = [];
62
+ const instructions: string[] = [];
63
+ let shouldRunPackageManagerInstall = false;
64
+ const creationDirectory = path.resolve(process.cwd(), args.name ?? "");
65
+
66
+ if (args.site) {
67
+ const gitDirectory =
68
+ creationDirectory !== process.cwd()
69
+ ? path.basename(creationDirectory)
70
+ : "my-site";
71
+ const message =
72
+ "The --site option is no longer supported.\n" +
73
+ "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
74
+ "```\n" +
75
+ `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
76
+ `cd ${gitDirectory}\n` +
77
+ "```\n\n" +
78
+ "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
79
+ "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
80
+ throw new CommandLineArgsError(message);
81
+ }
82
+
83
+ // TODO: make sure args.name is a valid identifier for a worker name
84
+ const workerName = path
85
+ .basename(creationDirectory)
86
+ .toLowerCase()
87
+ .replaceAll(/[^a-z0-9\-_]/gm, "-");
88
+
89
+ const packageManager = await getPackageManager(creationDirectory);
90
+
91
+ // TODO: ask which directory to make the worker in (defaults to args.name)
92
+ // TODO: if args.name isn't provided, ask what to name the worker
93
+
94
+ const wranglerTomlDestination = path.join(
95
+ creationDirectory,
96
+ "./wrangler.toml"
97
+ );
98
+ let justCreatedWranglerToml = false;
99
+
100
+ if (fs.existsSync(wranglerTomlDestination)) {
101
+ logger.warn(
102
+ `${path.relative(process.cwd(), wranglerTomlDestination)} already exists!`
103
+ );
104
+ const shouldContinue = await confirm(
105
+ "Do you want to continue initializing this project?"
106
+ );
107
+ if (!shouldContinue) {
108
+ return;
109
+ }
110
+ } else {
111
+ await mkdir(creationDirectory, { recursive: true });
112
+ const compatibilityDate = new Date().toISOString().substring(0, 10);
113
+
114
+ try {
115
+ await writeFile(
116
+ wranglerTomlDestination,
117
+ TOML.stringify({
118
+ name: workerName,
119
+ compatibility_date: compatibilityDate,
120
+ }) + "\n"
121
+ );
122
+
123
+ logger.log(
124
+ `✨ Created ${path.relative(process.cwd(), wranglerTomlDestination)}`
125
+ );
126
+ justCreatedWranglerToml = true;
127
+ } catch (err) {
128
+ throw new Error(
129
+ `Failed to create ${path.relative(
130
+ process.cwd(),
131
+ wranglerTomlDestination
132
+ )}.\n${(err as Error).message ?? err}`
133
+ );
134
+ }
135
+ }
136
+
137
+ const yesFlag = args.yes ?? false;
138
+
139
+ if (!(await isInsideGitRepo(creationDirectory)) && (await isGitInstalled())) {
140
+ const shouldInitGit =
141
+ yesFlag ||
142
+ (await confirm("Would you like to use git to manage this Worker?"));
143
+ if (shouldInitGit) {
144
+ await initializeGit(creationDirectory);
145
+ await writeFile(
146
+ path.join(creationDirectory, ".gitignore"),
147
+ readFileSync(path.join(__dirname, "../templates/gitignore"))
148
+ );
149
+ logger.log(
150
+ args.name && args.name !== "."
151
+ ? `✨ Initialized git repository at ${path.relative(
152
+ process.cwd(),
153
+ creationDirectory
154
+ )}`
155
+ : `✨ Initialized git repository`
156
+ );
157
+ }
158
+ }
159
+
160
+ const isolatedInit = !!args.name;
161
+ let pathToPackageJson = await findPath(
162
+ isolatedInit,
163
+ creationDirectory,
164
+ "package.json"
165
+ );
166
+ let shouldCreatePackageJson = false;
167
+
168
+ if (!pathToPackageJson) {
169
+ // If no package.json exists, ask to create one
170
+ shouldCreatePackageJson =
171
+ yesFlag ||
172
+ (await confirm("No package.json found. Would you like to create one?"));
173
+
174
+ if (shouldCreatePackageJson) {
175
+ await writeFile(
176
+ path.join(creationDirectory, "./package.json"),
177
+ JSON.stringify(
178
+ {
179
+ name: workerName,
180
+ version: "0.0.0",
181
+ devDependencies: {
182
+ wrangler: wranglerVersion,
183
+ },
184
+ private: true,
185
+ },
186
+ null,
187
+ " "
188
+ ) + "\n"
189
+ );
190
+
191
+ shouldRunPackageManagerInstall = true;
192
+ pathToPackageJson = path.join(creationDirectory, "package.json");
193
+ logger.log(
194
+ `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
195
+ );
196
+ } else {
197
+ return;
198
+ }
199
+ } else {
200
+ // If package.json exists and wrangler isn't installed,
201
+ // then ask to add wrangler to devDependencies
202
+ const packageJson = parsePackageJSON(
203
+ readFileSync(pathToPackageJson),
204
+ pathToPackageJson
205
+ );
206
+ if (
207
+ !(
208
+ packageJson.devDependencies?.wrangler ||
209
+ packageJson.dependencies?.wrangler
210
+ )
211
+ ) {
212
+ const shouldInstall =
213
+ yesFlag ||
214
+ (await confirm(
215
+ `Would you like to install wrangler into ${path.relative(
216
+ process.cwd(),
217
+ pathToPackageJson
218
+ )}?`
219
+ ));
220
+ if (shouldInstall) {
221
+ devDepsToInstall.push(`wrangler@${wranglerVersion}`);
222
+ }
223
+ }
224
+ }
225
+
226
+ let isTypescriptProject = false;
227
+ let pathToTSConfig = await findPath(
228
+ isolatedInit,
229
+ creationDirectory,
230
+ "tsconfig.json"
231
+ );
232
+ if (!pathToTSConfig) {
233
+ // If there's no tsconfig, offer to create one
234
+ // and install @cloudflare/workers-types
235
+ if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
236
+ isTypescriptProject = true;
237
+ await writeFile(
238
+ path.join(creationDirectory, "./tsconfig.json"),
239
+ readFileSync(path.join(__dirname, "../templates/tsconfig.json"))
240
+ );
241
+ devDepsToInstall.push("@cloudflare/workers-types");
242
+ devDepsToInstall.push("typescript");
243
+ pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
244
+ logger.log(`✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`);
245
+ }
246
+ } else {
247
+ isTypescriptProject = true;
248
+ // If there's a tsconfig, check if @cloudflare/workers-types
249
+ // is already installed, and offer to install it if not
250
+ const packageJson = parsePackageJSON(
251
+ readFileSync(pathToPackageJson),
252
+ pathToPackageJson
253
+ );
254
+ if (
255
+ !(
256
+ packageJson.devDependencies?.["@cloudflare/workers-types"] ||
257
+ packageJson.dependencies?.["@cloudflare/workers-types"]
258
+ )
259
+ ) {
260
+ const shouldInstall = await confirm(
261
+ "Would you like to install the type definitions for Workers into your package.json?"
262
+ );
263
+ if (shouldInstall) {
264
+ devDepsToInstall.push("@cloudflare/workers-types");
265
+ // We don't update the tsconfig.json because
266
+ // it could be complicated in existing projects
267
+ // and we don't want to break them. Instead, we simply
268
+ // tell the user that they need to update their tsconfig.json
269
+ instructions.push(
270
+ `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
271
+ process.cwd(),
272
+ pathToTSConfig
273
+ )}`
274
+ );
275
+ }
276
+ }
277
+ }
278
+
279
+ const packageJsonContent = parsePackageJSON(
280
+ readFileSync(pathToPackageJson),
281
+ pathToPackageJson
282
+ );
283
+ const shouldWritePackageJsonScripts =
284
+ !packageJsonContent.scripts?.start &&
285
+ !packageJsonContent.scripts?.publish &&
286
+ shouldCreatePackageJson;
287
+
288
+ /*
289
+ * Passes the array of accumulated devDeps to install through to
290
+ * the package manager. Also generates a human-readable list
291
+ * of packages it installed.
292
+ * If there are no devDeps to install, optionally runs
293
+ * the package manager's install command.
294
+ */
295
+ async function installPackages(
296
+ shouldRunInstall: boolean,
297
+ depsToInstall: string[]
298
+ ) {
299
+ //lets install the devDeps they asked for
300
+ //and run their package manager's install command if needed
301
+ if (depsToInstall.length > 0) {
302
+ const formatter = new Intl.ListFormat("en", {
303
+ style: "long",
304
+ type: "conjunction",
305
+ });
306
+ await packageManager.addDevDeps(...depsToInstall);
307
+ const versionlessPackages = depsToInstall.map((dep) =>
308
+ dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
309
+ );
310
+
311
+ logger.log(
312
+ `✨ Installed ${formatter.format(
313
+ versionlessPackages
314
+ )} into devDependencies`
315
+ );
316
+ } else {
317
+ if (shouldRunInstall) {
318
+ await packageManager.install();
319
+ }
320
+ }
321
+ }
322
+
323
+ async function writePackageJsonScriptsAndUpdateWranglerToml(
324
+ isWritingScripts: boolean,
325
+ isCreatingWranglerToml: boolean,
326
+ packagePath: string,
327
+ scriptPath: string,
328
+ extraToml: TOML.JsonMap
329
+ ) {
330
+ if (isCreatingWranglerToml) {
331
+ // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
332
+ const parsedWranglerToml = parseTOML(
333
+ readFileSync(wranglerTomlDestination)
334
+ );
335
+ const newToml = {
336
+ name: parsedWranglerToml.name,
337
+ main: scriptPath,
338
+ compatibility_date: parsedWranglerToml.compatibility_date,
339
+ ...extraToml,
340
+ };
341
+ fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
342
+ }
343
+ const isNamedWorker =
344
+ isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
345
+
346
+ if (isWritingScripts) {
347
+ await writeFile(
348
+ packagePath,
349
+ JSON.stringify(
350
+ {
351
+ ...packageJsonContent,
352
+ scripts: {
353
+ ...packageJsonContent.scripts,
354
+ start: isCreatingWranglerToml
355
+ ? `wrangler dev`
356
+ : `wrangler dev ${scriptPath}`,
357
+ deploy: isCreatingWranglerToml
358
+ ? `wrangler publish`
359
+ : `wrangler publish ${scriptPath}`,
360
+ },
361
+ },
362
+ null,
363
+ 2
364
+ ) + "\n"
365
+ );
366
+ instructions.push(
367
+ `\nTo start developing your Worker, run \`${
368
+ isNamedWorker ? `cd ${args.name} && ` : ""
369
+ }npm start\``
370
+ );
371
+ instructions.push(
372
+ `To publish your Worker to the Internet, run \`npm run deploy\``
373
+ );
374
+ } else {
375
+ instructions.push(
376
+ `\nTo start developing your Worker, run \`npx wrangler dev\`${
377
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
378
+ }`
379
+ );
380
+ instructions.push(
381
+ `To publish your Worker to the Internet, run \`npx wrangler publish\`${
382
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
383
+ }`
384
+ );
385
+ }
386
+ }
387
+
388
+ async function getNewWorkerType(newWorkerFilename: string) {
389
+ return select(
390
+ `Would you like to create a Worker at ${newWorkerFilename}?`,
391
+ [
392
+ {
393
+ value: "none",
394
+ label: "None",
395
+ },
396
+ {
397
+ value: "fetch",
398
+ label: "Fetch handler",
399
+ },
400
+ {
401
+ value: "scheduled",
402
+ label: "Scheduled handler",
403
+ },
404
+ ],
405
+ 1
406
+ ) as Promise<"none" | "fetch" | "scheduled">;
407
+ }
408
+
409
+ function getNewWorkerTemplate(
410
+ lang: "js" | "ts",
411
+ workerType: "fetch" | "scheduled"
412
+ ) {
413
+ const templates = {
414
+ "js-fetch": "new-worker.js",
415
+ "js-scheduled": "new-worker-scheduled.js",
416
+ "ts-fetch": "new-worker.ts",
417
+ "ts-scheduled": "new-worker-scheduled.ts",
418
+ };
419
+
420
+ return templates[`${lang}-${workerType}`];
421
+ }
422
+
423
+ function getNewWorkerToml(workerType: "fetch" | "scheduled"): TOML.JsonMap {
424
+ if (workerType === "scheduled") {
425
+ return {
426
+ triggers: {
427
+ crons: ["1 * * * *"],
428
+ },
429
+ };
430
+ }
431
+
432
+ return {};
433
+ }
434
+
435
+ if (isTypescriptProject) {
436
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
437
+ const newWorkerFilename = path.relative(
438
+ process.cwd(),
439
+ path.join(creationDirectory, "./src/index.ts")
440
+ );
441
+
442
+ const newWorkerType = yesFlag
443
+ ? "fetch"
444
+ : await getNewWorkerType(newWorkerFilename);
445
+
446
+ if (newWorkerType !== "none") {
447
+ const template = getNewWorkerTemplate("ts", newWorkerType);
448
+
449
+ await mkdir(path.join(creationDirectory, "./src"), {
450
+ recursive: true,
451
+ });
452
+ await writeFile(
453
+ path.join(creationDirectory, "./src/index.ts"),
454
+ readFileSync(path.join(__dirname, `../templates/${template}`))
455
+ );
456
+
457
+ logger.log(
458
+ `✨ Created ${path.relative(
459
+ process.cwd(),
460
+ path.join(creationDirectory, "./src/index.ts")
461
+ )}`
462
+ );
463
+
464
+ await writePackageJsonScriptsAndUpdateWranglerToml(
465
+ shouldWritePackageJsonScripts,
466
+ justCreatedWranglerToml,
467
+ pathToPackageJson,
468
+ "src/index.ts",
469
+ getNewWorkerToml(newWorkerType)
470
+ );
471
+ }
472
+ }
473
+ } else {
474
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
475
+ const newWorkerFilename = path.relative(
476
+ process.cwd(),
477
+ path.join(creationDirectory, "./src/index.js")
478
+ );
479
+
480
+ const newWorkerType = yesFlag
481
+ ? "fetch"
482
+ : await getNewWorkerType(newWorkerFilename);
483
+
484
+ if (newWorkerType !== "none") {
485
+ const template = getNewWorkerTemplate("js", newWorkerType);
486
+
487
+ await mkdir(path.join(creationDirectory, "./src"), {
488
+ recursive: true,
489
+ });
490
+ await writeFile(
491
+ path.join(creationDirectory, "./src/index.js"),
492
+ readFileSync(path.join(__dirname, `../templates/${template}`))
493
+ );
494
+
495
+ logger.log(
496
+ `✨ Created ${path.relative(
497
+ process.cwd(),
498
+ path.join(creationDirectory, "./src/index.js")
499
+ )}`
500
+ );
501
+
502
+ await writePackageJsonScriptsAndUpdateWranglerToml(
503
+ shouldWritePackageJsonScripts,
504
+ justCreatedWranglerToml,
505
+ pathToPackageJson,
506
+ "src/index.js",
507
+ getNewWorkerToml(newWorkerType)
508
+ );
509
+ }
510
+ }
511
+ }
512
+ // install packages as the final step of init
513
+ try {
514
+ await installPackages(shouldRunPackageManagerInstall, devDepsToInstall);
515
+ } catch (e) {
516
+ // fetching packages could fail due to loss of internet, etc
517
+ // we should let folks know we failed to fetch, but their
518
+ // workers project is still ready to go
519
+ logger.error(e instanceof Error ? e.message : e);
520
+ instructions.push(
521
+ "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
522
+ );
523
+ }
524
+
525
+ // let users know what to do now
526
+ instructions.forEach((instruction) => logger.log(instruction));
527
+ }
528
+
529
+ /**
530
+ * Find the path to the given `basename` file from the `cwd`.
531
+ *
532
+ * If `isolatedInit` is true then we only look in the `cwd` directory for the file.
533
+ * Otherwise we also search up the tree.
534
+ */
535
+ async function findPath(
536
+ isolatedInit: boolean,
537
+ cwd: string,
538
+ basename: string
539
+ ): Promise<string | undefined> {
540
+ if (isolatedInit) {
541
+ return fs.existsSync(path.resolve(cwd, basename))
542
+ ? path.resolve(cwd, basename)
543
+ : undefined;
544
+ } else {
545
+ return await findUp(basename, {
546
+ cwd: cwd,
547
+ });
548
+ }
549
+ }