wrangler 0.0.0-e8e684c7 → 0.0.0-e9106dfa5

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