wrangler 0.0.0-e61fba8 → 0.0.0-e665ccc3

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 (339) hide show
  1. package/README.md +24 -4
  2. package/bin/wrangler.js +170 -62
  3. package/miniflare-dist/index.mjs +1643 -83
  4. package/package.json +198 -154
  5. package/src/__tests__/access.test.ts +25 -0
  6. package/src/__tests__/api-dev.test.ts +238 -0
  7. package/src/__tests__/api-devregistry.test.ts +121 -0
  8. package/src/__tests__/api.test.ts +102 -0
  9. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  10. package/src/__tests__/config-cache.test.ts +30 -24
  11. package/src/__tests__/configuration.test.ts +4506 -3476
  12. package/src/__tests__/constellation.test.ts +371 -0
  13. package/src/__tests__/d1/d1.test.ts +82 -0
  14. package/src/__tests__/d1/execute.test.ts +66 -0
  15. package/src/__tests__/d1/migrate.test.ts +257 -0
  16. package/src/__tests__/d1/splitter.test.ts +255 -0
  17. package/src/__tests__/delete.test.ts +272 -0
  18. package/src/__tests__/deployments.test.ts +369 -0
  19. package/src/__tests__/dev.test.tsx +1590 -983
  20. package/src/__tests__/generate.test.ts +237 -0
  21. package/src/__tests__/get-host-from-url.test.ts +16 -0
  22. package/src/__tests__/guess-worker-format.test.ts +103 -68
  23. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  24. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  25. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  26. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  27. package/src/__tests__/helpers/mock-bin.ts +20 -20
  28. package/src/__tests__/helpers/mock-console.ts +64 -39
  29. package/src/__tests__/helpers/mock-dialogs.ts +88 -79
  30. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  31. package/src/__tests__/helpers/mock-get-zone-from-host.ts +11 -0
  32. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  33. package/src/__tests__/helpers/mock-istty.ts +65 -18
  34. package/src/__tests__/helpers/mock-known-routes.ts +12 -0
  35. package/src/__tests__/helpers/mock-kv.ts +41 -28
  36. package/src/__tests__/helpers/mock-oauth-flow.ts +241 -233
  37. package/src/__tests__/helpers/mock-process.ts +34 -0
  38. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  39. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  40. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  41. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  42. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  43. package/src/__tests__/helpers/msw/handlers/deployments.ts +160 -0
  44. package/src/__tests__/helpers/msw/handlers/namespaces.ts +81 -0
  45. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  46. package/src/__tests__/helpers/msw/handlers/r2.ts +60 -0
  47. package/src/__tests__/helpers/msw/handlers/script.ts +56 -0
  48. package/src/__tests__/helpers/msw/handlers/user.ts +52 -0
  49. package/src/__tests__/helpers/msw/handlers/zones.ts +20 -0
  50. package/src/__tests__/helpers/msw/index.ts +52 -0
  51. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  52. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  53. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  54. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  55. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  56. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  57. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  58. package/src/__tests__/helpers/worker-scripts/parent-worker.js +11 -0
  59. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  60. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  61. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  62. package/src/__tests__/https-options.test.ts +142 -109
  63. package/src/__tests__/index.test.ts +262 -237
  64. package/src/__tests__/init.test.ts +3167 -1608
  65. package/src/__tests__/jest.setup.ts +152 -50
  66. package/src/__tests__/kv.test.ts +1789 -1492
  67. package/src/__tests__/logger.test.ts +167 -75
  68. package/src/__tests__/logout.test.ts +47 -0
  69. package/src/__tests__/metrics.test.ts +493 -0
  70. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  71. package/src/__tests__/middleware.test.ts +816 -0
  72. package/src/__tests__/mtls-certificates.test.ts +589 -0
  73. package/src/__tests__/package-manager.test.ts +303 -303
  74. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  75. package/src/__tests__/pages/functions-build.test.ts +528 -0
  76. package/src/__tests__/pages/pages.test.ts +81 -0
  77. package/src/__tests__/pages/project-create.test.ts +63 -0
  78. package/src/__tests__/pages/project-list.test.ts +110 -0
  79. package/src/__tests__/pages/project-upload.test.ts +500 -0
  80. package/src/__tests__/pages/publish.test.ts +2864 -0
  81. package/src/__tests__/pages-deployment-tail.test.ts +957 -0
  82. package/src/__tests__/parse.test.ts +358 -252
  83. package/src/__tests__/paths.test.ts +39 -0
  84. package/src/__tests__/publish.test.ts +8716 -5687
  85. package/src/__tests__/pubsub.test.ts +496 -0
  86. package/src/__tests__/queues.test.ts +532 -0
  87. package/src/__tests__/r2.test.ts +369 -228
  88. package/src/__tests__/route.test.ts +18 -18
  89. package/src/__tests__/secret.test.ts +681 -469
  90. package/src/__tests__/tail.test.ts +866 -567
  91. package/src/__tests__/test-old-node-version.js +31 -0
  92. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  93. package/src/__tests__/tsconfig-sanity.ts +12 -0
  94. package/src/__tests__/tsconfig.json +8 -0
  95. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  96. package/src/__tests__/type-generation.test.ts +234 -0
  97. package/src/__tests__/user.test.ts +107 -120
  98. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  99. package/src/__tests__/validate-dev-props.test.ts +56 -0
  100. package/src/__tests__/version.test.ts +35 -0
  101. package/src/__tests__/whoami.test.tsx +165 -132
  102. package/src/__tests__/worker-namespace.test.ts +340 -0
  103. package/src/abort.d.ts +1 -1
  104. package/src/api/dev.ts +321 -0
  105. package/src/api/index.ts +11 -0
  106. package/src/api/mtls-certificate.ts +148 -0
  107. package/src/api/pages/create-worker-bundle-contents.ts +77 -0
  108. package/src/api/pages/index.ts +5 -0
  109. package/src/api/pages/publish.tsx +371 -0
  110. package/src/bundle-reporter.ts +68 -0
  111. package/src/bundle.ts +890 -165
  112. package/src/cfetch/index.ts +120 -83
  113. package/src/cfetch/internal.ts +208 -92
  114. package/src/cli.ts +23 -8
  115. package/src/config/config.ts +244 -196
  116. package/src/config/diagnostics.ts +61 -61
  117. package/src/config/environment.ts +562 -357
  118. package/src/config/index.ts +374 -196
  119. package/src/config/validation-helpers.ts +379 -366
  120. package/src/config/validation.ts +2197 -1376
  121. package/src/config-cache.ts +81 -41
  122. package/src/constellation/createProject.tsx +51 -0
  123. package/src/constellation/deleteProject.ts +51 -0
  124. package/src/constellation/deleteProjectModel.ts +68 -0
  125. package/src/constellation/index.ts +75 -0
  126. package/src/constellation/listCatalog.tsx +35 -0
  127. package/src/constellation/listModel.tsx +41 -0
  128. package/src/constellation/listProject.tsx +28 -0
  129. package/src/constellation/listRuntime.tsx +28 -0
  130. package/src/constellation/options.ts +17 -0
  131. package/src/constellation/types.ts +17 -0
  132. package/src/constellation/uploadModel.tsx +64 -0
  133. package/src/constellation/utils.ts +90 -0
  134. package/src/create-worker-preview.ts +250 -142
  135. package/src/create-worker-upload-form.ts +347 -238
  136. package/src/d1/backups.tsx +219 -0
  137. package/src/d1/constants.ts +2 -0
  138. package/src/d1/create.tsx +70 -0
  139. package/src/d1/delete.ts +53 -0
  140. package/src/d1/execute.tsx +357 -0
  141. package/src/d1/formatTimeAgo.ts +14 -0
  142. package/src/d1/index.ts +100 -0
  143. package/src/d1/list.tsx +62 -0
  144. package/src/d1/migrations/apply.tsx +212 -0
  145. package/src/d1/migrations/create.tsx +79 -0
  146. package/src/d1/migrations/helpers.ts +169 -0
  147. package/src/d1/migrations/index.ts +3 -0
  148. package/src/d1/migrations/list.tsx +95 -0
  149. package/src/d1/migrations/options.ts +23 -0
  150. package/src/d1/options.ts +22 -0
  151. package/src/d1/splitter.ts +161 -0
  152. package/src/d1/types.ts +25 -0
  153. package/src/d1/utils.ts +49 -0
  154. package/src/delete.ts +100 -0
  155. package/src/deployments.ts +368 -0
  156. package/src/deprecated/index.ts +144 -0
  157. package/src/dev/dev-vars.ts +20 -17
  158. package/src/dev/dev.tsx +535 -325
  159. package/src/dev/get-local-persistence-path.ts +31 -0
  160. package/src/dev/local.tsx +932 -301
  161. package/src/dev/remote.tsx +623 -228
  162. package/src/dev/start-server.ts +545 -0
  163. package/src/dev/use-esbuild.ts +194 -94
  164. package/src/dev/validate-dev-props.ts +40 -0
  165. package/src/dev-registry.ts +202 -0
  166. package/src/dev.tsx +934 -0
  167. package/src/dialogs.ts +136 -0
  168. package/src/dispatch-namespace.ts +211 -0
  169. package/src/docs/helpers.ts +50 -0
  170. package/src/docs/index.ts +54 -0
  171. package/src/durable.ts +87 -87
  172. package/src/entry.ts +253 -231
  173. package/src/environment-variables/factory.ts +89 -0
  174. package/src/environment-variables/misc-variables.ts +30 -0
  175. package/src/errors.ts +6 -6
  176. package/src/generate/index.ts +298 -0
  177. package/src/git-client.ts +135 -0
  178. package/src/global-wrangler-config-path.ts +26 -0
  179. package/src/https-options.ts +84 -80
  180. package/src/index.ts +768 -0
  181. package/src/init.ts +1037 -0
  182. package/src/inspect.ts +816 -595
  183. package/src/intl-polyfill.d.ts +123 -123
  184. package/src/is-ci.ts +14 -0
  185. package/src/is-interactive.ts +16 -0
  186. package/src/jest.d.ts +4 -0
  187. package/src/kv/helpers.ts +433 -0
  188. package/src/kv/index.ts +594 -0
  189. package/src/logger.ts +100 -43
  190. package/src/metrics/index.ts +5 -0
  191. package/src/metrics/metrics-config.ts +239 -0
  192. package/src/metrics/metrics-dispatcher.ts +96 -0
  193. package/src/metrics/metrics-usage-headers.ts +24 -0
  194. package/src/metrics/send-event.ts +99 -0
  195. package/src/miniflare-cli/assets.ts +255 -0
  196. package/src/miniflare-cli/index.ts +202 -33
  197. package/src/miniflare-cli/request-context.ts +18 -18
  198. package/src/miniflare-cli/tsconfig.json +9 -0
  199. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  200. package/src/miniflare-cli/types.ts +11 -0
  201. package/src/module-collection.ts +290 -215
  202. package/src/mtls-certificate/cli.ts +155 -0
  203. package/src/open-in-browser.ts +4 -6
  204. package/src/package-manager.ts +173 -128
  205. package/src/pages/build.ts +423 -0
  206. package/src/pages/buildFunctions.ts +140 -0
  207. package/src/pages/constants.ts +18 -0
  208. package/src/pages/deployment-tails.ts +281 -0
  209. package/src/pages/deployments.tsx +84 -0
  210. package/src/pages/dev.ts +734 -0
  211. package/src/pages/errors.ts +67 -0
  212. package/src/pages/functions/buildPlugin.ts +114 -0
  213. package/src/pages/functions/buildWorker.ts +350 -0
  214. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  215. package/src/pages/functions/filepath-routing.ts +189 -0
  216. package/src/pages/functions/identifiers.ts +78 -0
  217. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  218. package/src/pages/functions/routes-consolidation.ts +73 -0
  219. package/src/pages/functions/routes-transformation.test.ts +282 -0
  220. package/src/pages/functions/routes-transformation.ts +115 -0
  221. package/src/pages/functions/routes-validation.test.ts +403 -0
  222. package/src/pages/functions/routes-validation.ts +202 -0
  223. package/src/pages/functions/routes.ts +151 -0
  224. package/src/pages/functions/tsconfig.json +8 -0
  225. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  226. package/src/pages/functions.ts +86 -0
  227. package/src/pages/hash.ts +13 -0
  228. package/src/pages/index.ts +102 -0
  229. package/src/pages/projects.tsx +159 -0
  230. package/src/pages/prompt-select-project.tsx +31 -0
  231. package/src/pages/publish.tsx +267 -0
  232. package/src/pages/types.ts +46 -0
  233. package/src/pages/upload.tsx +469 -0
  234. package/src/pages/utils.ts +23 -0
  235. package/src/parse.ts +225 -139
  236. package/src/paths.ts +53 -8
  237. package/src/proxy.ts +623 -407
  238. package/src/publish/index.ts +274 -0
  239. package/src/publish/publish.ts +1065 -0
  240. package/src/pubsub/index.ts +286 -0
  241. package/src/pubsub/pubsub-commands.ts +623 -0
  242. package/src/queues/cli/commands/consumer/add.ts +71 -0
  243. package/src/queues/cli/commands/consumer/index.ts +19 -0
  244. package/src/queues/cli/commands/consumer/remove.ts +31 -0
  245. package/src/queues/cli/commands/create.ts +25 -0
  246. package/src/queues/cli/commands/delete.ts +26 -0
  247. package/src/queues/cli/commands/index.ts +35 -0
  248. package/src/queues/cli/commands/list.ts +25 -0
  249. package/src/queues/client.ts +136 -0
  250. package/src/queues/utils.ts +18 -0
  251. package/src/r2/constants.ts +4 -0
  252. package/src/r2/helpers.ts +132 -0
  253. package/src/r2/index.ts +289 -0
  254. package/src/routes.ts +140 -0
  255. package/src/secret/index.ts +377 -0
  256. package/src/selfsigned.d.ts +23 -23
  257. package/src/sites.ts +484 -0
  258. package/src/tail/createTail.ts +415 -0
  259. package/src/tail/filters.ts +109 -111
  260. package/src/tail/index.ts +208 -296
  261. package/src/tail/printing.ts +116 -51
  262. package/src/traverse-module-graph.ts +54 -0
  263. package/src/tsconfig-sanity.ts +16 -0
  264. package/src/type-generation.ts +181 -0
  265. package/src/update-check.ts +11 -11
  266. package/src/user/access.ts +68 -0
  267. package/src/user/auth-variables.ts +113 -0
  268. package/src/user/choose-account.tsx +39 -0
  269. package/src/user/generate-auth-url.ts +33 -0
  270. package/src/user/generate-random-state.ts +16 -0
  271. package/src/user/index.ts +2 -0
  272. package/src/user/user.ts +1234 -0
  273. package/src/utils/collectKeyValues.ts +14 -0
  274. package/src/utils/render.ts +93 -0
  275. package/src/whoami.ts +135 -0
  276. package/src/worker.ts +205 -107
  277. package/src/yargs-types.ts +37 -0
  278. package/src/zones.ts +158 -40
  279. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  280. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  281. package/templates/__tests__/tsconfig.json +8 -0
  282. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  283. package/templates/checked-fetch.js +23 -0
  284. package/templates/d1-beta-facade.js +244 -0
  285. package/templates/facade.d.ts +14 -0
  286. package/templates/first-party-worker-module-facade.ts +19 -0
  287. package/templates/format-dev-errors.ts +34 -0
  288. package/templates/gitignore +1 -0
  289. package/templates/init-tests/test-jest-new-worker.js +23 -0
  290. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  291. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  292. package/templates/middleware/common.ts +62 -0
  293. package/templates/middleware/loader-modules.ts +84 -0
  294. package/templates/middleware/loader-sw.ts +233 -0
  295. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  296. package/templates/middleware/middleware-pretty-error.ts +40 -0
  297. package/templates/middleware/middleware-scheduled.ts +15 -0
  298. package/templates/new-worker-scheduled.js +3 -3
  299. package/templates/new-worker-scheduled.ts +15 -15
  300. package/templates/new-worker.js +3 -3
  301. package/templates/new-worker.ts +18 -15
  302. package/templates/no-op-worker.js +10 -0
  303. package/templates/pages-dev-pipeline.ts +31 -0
  304. package/templates/pages-dev-util.ts +52 -0
  305. package/templates/pages-shim.ts +12 -0
  306. package/templates/pages-template-plugin.ts +180 -0
  307. package/templates/pages-template-worker.ts +189 -0
  308. package/templates/serve-static-assets.ts +66 -0
  309. package/templates/service-bindings-module-facade.js +55 -0
  310. package/templates/service-bindings-sw-facade.js +42 -0
  311. package/templates/tsconfig-sanity.ts +11 -0
  312. package/templates/tsconfig.init.json +105 -0
  313. package/templates/tsconfig.json +6 -103
  314. package/templates/tsconfig.tsbuildinfo +1 -0
  315. package/wrangler-dist/cli.d.ts +1652 -0
  316. package/wrangler-dist/cli.js +139094 -111923
  317. package/wrangler-dist/wasm-sync.wasm +0 -0
  318. package/pages/functions/buildPlugin.ts +0 -105
  319. package/pages/functions/buildWorker.ts +0 -151
  320. package/pages/functions/filepath-routing.ts +0 -189
  321. package/pages/functions/identifiers.ts +0 -78
  322. package/pages/functions/routes.ts +0 -156
  323. package/pages/functions/template-plugin.ts +0 -147
  324. package/pages/functions/template-worker.ts +0 -143
  325. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  326. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  327. package/src/__tests__/pages.test.ts +0 -754
  328. package/src/dialogs.tsx +0 -135
  329. package/src/environment-variables.ts +0 -35
  330. package/src/index.tsx +0 -2859
  331. package/src/kv.ts +0 -408
  332. package/src/miniflare-cli/enum-keys.ts +0 -17
  333. package/src/pages.tsx +0 -2093
  334. package/src/publish.ts +0 -721
  335. package/src/r2.ts +0 -50
  336. package/src/sites.tsx +0 -326
  337. package/src/user.tsx +0 -1214
  338. package/src/whoami.tsx +0 -71
  339. package/templates/static-asset-facade.js +0 -43
package/src/init.ts ADDED
@@ -0,0 +1,1037 @@
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 { fetchResult } from "./cfetch";
9
+ import { fetchDashboardScript } from "./cfetch/internal";
10
+ import { readConfig } from "./config";
11
+ import { confirm, select } from "./dialogs";
12
+ import { initializeGit, getGitVersioon, isInsideGitRepo } from "./git-client";
13
+ import { logger } from "./logger";
14
+ import { getPackageManager } from "./package-manager";
15
+ import { parsePackageJSON, parseTOML, readFileSync } from "./parse";
16
+ import { getBasePath } from "./paths";
17
+ import { requireAuth } from "./user";
18
+ import { CommandLineArgsError, printWranglerBanner } from "./index";
19
+
20
+ import type { RawConfig } from "./config";
21
+ import type { Route, SimpleRoute } from "./config/environment";
22
+ import type {
23
+ WorkerMetadata,
24
+ WorkerMetadataBinding,
25
+ } from "./create-worker-upload-form";
26
+ import type { PackageManager } from "./package-manager";
27
+ import type { PackageJSON } from "./parse";
28
+ import type {
29
+ CommonYargsArgv,
30
+ StrictYargsOptionsToInterface,
31
+ } from "./yargs-types";
32
+
33
+ export function initOptions(yargs: CommonYargsArgv) {
34
+ return yargs
35
+ .positional("name", {
36
+ describe: "The name of your worker",
37
+ type: "string",
38
+ })
39
+ .option("type", {
40
+ describe: "The type of worker to create",
41
+ type: "string",
42
+ choices: ["rust", "javascript", "webpack"],
43
+ hidden: true,
44
+ deprecated: true,
45
+ })
46
+ .option("site", {
47
+ hidden: true,
48
+ type: "boolean",
49
+ deprecated: true,
50
+ })
51
+ .option("yes", {
52
+ describe: 'Answer "yes" to any prompts for new projects',
53
+ type: "boolean",
54
+ alias: "y",
55
+ })
56
+ .option("from-dash", {
57
+ describe:
58
+ "The name of the Worker you wish to download from the Cloudflare dashboard for local development.",
59
+ type: "string",
60
+ requiresArg: true,
61
+ });
62
+ }
63
+
64
+ type InitArgs = StrictYargsOptionsToInterface<typeof initOptions>;
65
+
66
+ export type ServiceMetadataRes = {
67
+ id: string;
68
+ default_environment: {
69
+ environment: string;
70
+ created_on: string;
71
+ modified_on: string;
72
+ script: {
73
+ id: string;
74
+ tag: string;
75
+ etag: string;
76
+ handlers: string[];
77
+ modified_on: string;
78
+ created_on: string;
79
+ migration_tag: string;
80
+ usage_model: "bundled" | "unbound";
81
+ compatibility_date: string;
82
+ last_deployed_from?: "wrangler" | "dash" | "api";
83
+ placement_mode?: "smart";
84
+ };
85
+ };
86
+ created_on: string;
87
+ modified_on: string;
88
+ usage_model: "bundled" | "unbound";
89
+ environments: [
90
+ {
91
+ environment: string;
92
+ created_on: string;
93
+ modified_on: string;
94
+ }
95
+ ];
96
+ };
97
+
98
+ export type RawSimpleRoute = { pattern: string };
99
+ export type RawRoutes = (RawSimpleRoute | Exclude<Route, SimpleRoute>) & {
100
+ id: string;
101
+ };
102
+ export type RoutesRes = RawRoutes[];
103
+
104
+ export type CronTriggersRes = {
105
+ schedules: [
106
+ {
107
+ cron: string;
108
+ created_on: Date;
109
+ modified_on: Date;
110
+ }
111
+ ];
112
+ };
113
+
114
+ export async function initHandler(args: InitArgs) {
115
+ await printWranglerBanner();
116
+ if (args.type) {
117
+ let message = "The --type option is no longer supported.";
118
+ if (args.type === "webpack") {
119
+ message +=
120
+ "\nIf you wish to use webpack then you will need to create a custom build.";
121
+ // TODO: Add a link to docs
122
+ }
123
+ throw new CommandLineArgsError(message);
124
+ }
125
+
126
+ const devDepsToInstall: string[] = [];
127
+ const instructions: string[] = [];
128
+ let shouldRunPackageManagerInstall = false;
129
+ const fromDashScriptName = args.fromDash;
130
+ const creationDirectory = path.resolve(
131
+ process.cwd(),
132
+ (args.name ? args.name : fromDashScriptName) ?? ""
133
+ );
134
+
135
+ if (args.site) {
136
+ const gitDirectory =
137
+ creationDirectory !== process.cwd()
138
+ ? path.basename(creationDirectory)
139
+ : "my-site";
140
+ const message =
141
+ "The --site option is no longer supported.\n" +
142
+ "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
143
+ "```\n" +
144
+ `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
145
+ `cd ${gitDirectory}\n` +
146
+ "```\n\n" +
147
+ "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
148
+ "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
149
+ throw new CommandLineArgsError(message);
150
+ }
151
+
152
+ // TODO: make sure args.name is a valid identifier for a worker name
153
+ const workerName = path
154
+ .basename(creationDirectory)
155
+ .toLowerCase()
156
+ .replaceAll(/[^a-z0-9\-_]/gm, "-");
157
+
158
+ const packageManager = await getPackageManager(creationDirectory);
159
+
160
+ // TODO: ask which directory to make the worker in (defaults to args.name)
161
+ // TODO: if args.name isn't provided, ask what to name the worker
162
+ // Note: `--from-dash` will be a fallback creationDir/Worker name if none is provided.
163
+
164
+ const wranglerTomlDestination = path.join(
165
+ creationDirectory,
166
+ "./wrangler.toml"
167
+ );
168
+ let justCreatedWranglerToml = false;
169
+
170
+ let accountId = "";
171
+ let serviceMetadata: undefined | ServiceMetadataRes;
172
+
173
+ // If --from-dash, check that script actually exists
174
+ if (fromDashScriptName) {
175
+ const config = readConfig(args.config, args);
176
+ accountId = await requireAuth(config);
177
+ try {
178
+ serviceMetadata = await fetchResult<ServiceMetadataRes>(
179
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}`
180
+ );
181
+ } catch (err) {
182
+ if ((err as { code?: number }).code === 10090) {
183
+ throw new Error(
184
+ "wrangler couldn't find a Worker script with that name in your account.\nRun `wrangler whoami` to confirm you're logged into the correct account."
185
+ );
186
+ }
187
+ throw err;
188
+ }
189
+ }
190
+
191
+ if (fs.existsSync(wranglerTomlDestination)) {
192
+ let shouldContinue = false;
193
+ logger.warn(
194
+ `${path.relative(process.cwd(), wranglerTomlDestination)} already exists!`
195
+ );
196
+ if (!fromDashScriptName) {
197
+ shouldContinue = await confirm(
198
+ "Do you want to continue initializing this project?"
199
+ );
200
+ }
201
+ if (!shouldContinue) {
202
+ return;
203
+ }
204
+ } else {
205
+ await mkdir(creationDirectory, { recursive: true });
206
+ const compatibilityDate = new Date().toISOString().substring(0, 10);
207
+
208
+ try {
209
+ await writeFile(
210
+ wranglerTomlDestination,
211
+ TOML.stringify({
212
+ name: workerName,
213
+ compatibility_date: compatibilityDate,
214
+ }) + "\n"
215
+ );
216
+
217
+ logger.log(
218
+ `✨ Created ${path.relative(process.cwd(), wranglerTomlDestination)}`
219
+ );
220
+ justCreatedWranglerToml = true;
221
+ } catch (err) {
222
+ throw new Error(
223
+ `Failed to create ${path.relative(
224
+ process.cwd(),
225
+ wranglerTomlDestination
226
+ )}.\n${(err as Error).message ?? err}`
227
+ );
228
+ }
229
+ }
230
+
231
+ const yesFlag = args.yes ?? false;
232
+
233
+ if (!(await isInsideGitRepo(creationDirectory)) && (await getGitVersioon())) {
234
+ const shouldInitGit =
235
+ yesFlag ||
236
+ (await confirm("Would you like to use git to manage this Worker?"));
237
+ if (shouldInitGit) {
238
+ await initializeGit(creationDirectory);
239
+ await writeFile(
240
+ path.join(creationDirectory, ".gitignore"),
241
+ readFileSync(path.join(getBasePath(), "templates/gitignore"))
242
+ );
243
+ logger.log(
244
+ args.name && args.name !== "."
245
+ ? `✨ Initialized git repository at ${path.relative(
246
+ process.cwd(),
247
+ creationDirectory
248
+ )}`
249
+ : `✨ Initialized git repository`
250
+ );
251
+ }
252
+ }
253
+
254
+ const isolatedInit = !!args.name;
255
+ let pathToPackageJson = await findPath(
256
+ isolatedInit,
257
+ creationDirectory,
258
+ "package.json"
259
+ );
260
+ let shouldCreatePackageJson = false;
261
+ let shouldCreateTests = false;
262
+ let newWorkerTestType: "jest" | "vitest" = "jest";
263
+
264
+ if (!pathToPackageJson) {
265
+ // If no package.json exists, ask to create one
266
+ shouldCreatePackageJson =
267
+ yesFlag ||
268
+ (await confirm("No package.json found. Would you like to create one?"));
269
+
270
+ if (shouldCreatePackageJson) {
271
+ await writeFile(
272
+ path.join(creationDirectory, "./package.json"),
273
+ JSON.stringify(
274
+ {
275
+ name: workerName,
276
+ version: "0.0.0",
277
+ devDependencies: {
278
+ wrangler: wranglerVersion,
279
+ },
280
+ private: true,
281
+ },
282
+ null,
283
+ " "
284
+ ) + "\n"
285
+ );
286
+
287
+ shouldRunPackageManagerInstall = true;
288
+ pathToPackageJson = path.join(creationDirectory, "package.json");
289
+ logger.log(
290
+ `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
291
+ );
292
+ } else {
293
+ return;
294
+ }
295
+ } else {
296
+ // If package.json exists and wrangler isn't installed,
297
+ // then ask to add wrangler to devDependencies
298
+ const packageJson = parsePackageJSON(
299
+ readFileSync(pathToPackageJson),
300
+ pathToPackageJson
301
+ );
302
+ if (
303
+ !(
304
+ packageJson.devDependencies?.wrangler ||
305
+ packageJson.dependencies?.wrangler
306
+ )
307
+ ) {
308
+ const shouldInstall =
309
+ yesFlag ||
310
+ (await confirm(
311
+ `Would you like to install wrangler into ${path.relative(
312
+ process.cwd(),
313
+ pathToPackageJson
314
+ )}?`
315
+ ));
316
+ if (shouldInstall) {
317
+ devDepsToInstall.push(`wrangler@${wranglerVersion}`);
318
+ }
319
+ }
320
+ }
321
+
322
+ let isTypescriptProject = false;
323
+ let pathToTSConfig = await findPath(
324
+ isolatedInit,
325
+ creationDirectory,
326
+ "tsconfig.json"
327
+ );
328
+ if (!pathToTSConfig) {
329
+ // If there's no tsconfig, offer to create one
330
+ // and install @cloudflare/workers-types
331
+ if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
332
+ isTypescriptProject = true;
333
+ await writeFile(
334
+ path.join(creationDirectory, "./tsconfig.json"),
335
+ readFileSync(path.join(getBasePath(), "templates/tsconfig.init.json"))
336
+ );
337
+ devDepsToInstall.push("@cloudflare/workers-types");
338
+ devDepsToInstall.push("typescript");
339
+ pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
340
+ logger.log(`✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`);
341
+ }
342
+ } else {
343
+ isTypescriptProject = true;
344
+ // If there's a tsconfig, check if @cloudflare/workers-types
345
+ // is already installed, and offer to install it if not
346
+ const packageJson = parsePackageJSON(
347
+ readFileSync(pathToPackageJson),
348
+ pathToPackageJson
349
+ );
350
+ if (
351
+ !(
352
+ packageJson.devDependencies?.["@cloudflare/workers-types"] ||
353
+ packageJson.dependencies?.["@cloudflare/workers-types"]
354
+ )
355
+ ) {
356
+ const shouldInstall = await confirm(
357
+ "Would you like to install the type definitions for Workers into your package.json?"
358
+ );
359
+ if (shouldInstall) {
360
+ devDepsToInstall.push("@cloudflare/workers-types");
361
+ // We don't update the tsconfig.json because
362
+ // it could be complicated in existing projects
363
+ // and we don't want to break them. Instead, we simply
364
+ // tell the user that they need to update their tsconfig.json
365
+ instructions.push(
366
+ `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
367
+ process.cwd(),
368
+ pathToTSConfig
369
+ )}`
370
+ );
371
+ }
372
+ }
373
+ }
374
+
375
+ const packageJsonContent = parsePackageJSON(
376
+ readFileSync(pathToPackageJson),
377
+ pathToPackageJson
378
+ );
379
+ const shouldWritePackageJsonScripts =
380
+ !packageJsonContent.scripts?.start &&
381
+ !packageJsonContent.scripts?.publish &&
382
+ shouldCreatePackageJson;
383
+
384
+ async function writePackageJsonScriptsAndUpdateWranglerToml({
385
+ isWritingScripts,
386
+ isAddingTests,
387
+ testRunner,
388
+ isCreatingWranglerToml,
389
+ packagePath,
390
+ scriptPath,
391
+ extraToml,
392
+ }: {
393
+ isWritingScripts: boolean;
394
+ isAddingTests?: boolean;
395
+ testRunner?: "jest" | "vitest";
396
+ isCreatingWranglerToml: boolean;
397
+ packagePath: string;
398
+ scriptPath: string;
399
+ extraToml: TOML.JsonMap;
400
+ }) {
401
+ if (isAddingTests && !testRunner) {
402
+ logger.error("testRunner is required if isAddingTests");
403
+ }
404
+ if (isCreatingWranglerToml) {
405
+ // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
406
+ const parsedWranglerToml = parseTOML(
407
+ readFileSync(wranglerTomlDestination)
408
+ );
409
+ const newToml = {
410
+ name: parsedWranglerToml.name,
411
+ main: scriptPath,
412
+ compatibility_date: parsedWranglerToml.compatibility_date,
413
+ ...extraToml,
414
+ };
415
+ fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
416
+ }
417
+ const isNamedWorker =
418
+ isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
419
+ const isAddingTestScripts =
420
+ isAddingTests && !packageJsonContent.scripts?.test;
421
+ if (isWritingScripts) {
422
+ await writeFile(
423
+ packagePath,
424
+ JSON.stringify(
425
+ {
426
+ ...packageJsonContent,
427
+ scripts: {
428
+ ...packageJsonContent.scripts,
429
+ start: isCreatingWranglerToml
430
+ ? `wrangler dev`
431
+ : `wrangler dev ${scriptPath}`,
432
+ deploy: isCreatingWranglerToml
433
+ ? `wrangler publish`
434
+ : `wrangler publish ${scriptPath}`,
435
+ ...(isAddingTestScripts && { test: testRunner }),
436
+ },
437
+ } as PackageJSON,
438
+ null,
439
+ 2
440
+ ) + "\n"
441
+ );
442
+ instructions.push(
443
+ `\nTo start developing your Worker, run \`${
444
+ isNamedWorker ? `cd ${args.name || fromDashScriptName} && ` : ""
445
+ }npm start\``
446
+ );
447
+ if (isAddingTestScripts) {
448
+ instructions.push(`To start testing your Worker, run \`npm test\``);
449
+ }
450
+ instructions.push(
451
+ `To publish your Worker to the Internet, run \`npm run deploy\``
452
+ );
453
+ } else {
454
+ instructions.push(
455
+ `\nTo start developing your Worker, run \`npx wrangler dev\`${
456
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
457
+ }`
458
+ );
459
+ instructions.push(
460
+ `To publish your Worker to the Internet, run \`npx wrangler publish\`${
461
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
462
+ }`
463
+ );
464
+ }
465
+ }
466
+
467
+ if (isTypescriptProject) {
468
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
469
+ const newWorkerFilename = path.relative(
470
+ process.cwd(),
471
+ path.join(creationDirectory, "./src/index.ts")
472
+ );
473
+ if (fromDashScriptName) {
474
+ logger.warn(
475
+ "After running `wrangler init --from-dash`, modifying your worker via the Cloudflare dashboard is discouraged.\nEdits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish."
476
+ );
477
+
478
+ await mkdir(path.join(creationDirectory, "./src"), {
479
+ recursive: true,
480
+ });
481
+
482
+ const defaultEnvironment =
483
+ serviceMetadata?.default_environment.environment;
484
+ // I want the default environment, assuming it's the most up to date code.
485
+ const dashScript = await fetchDashboardScript(
486
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
487
+ );
488
+
489
+ await writeFile(
490
+ path.join(creationDirectory, "./src/index.ts"),
491
+ dashScript
492
+ );
493
+
494
+ await writePackageJsonScriptsAndUpdateWranglerToml({
495
+ isWritingScripts: shouldWritePackageJsonScripts,
496
+ isCreatingWranglerToml: justCreatedWranglerToml,
497
+ packagePath: pathToPackageJson,
498
+ scriptPath: "src/index.ts",
499
+ extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
500
+ defaultEnvironment,
501
+ environments: serviceMetadata?.environments,
502
+ })) as TOML.JsonMap,
503
+ });
504
+ } else {
505
+ const newWorkerType = yesFlag
506
+ ? "fetch"
507
+ : await getNewWorkerType(newWorkerFilename);
508
+
509
+ if (newWorkerType !== "none") {
510
+ const template = getNewWorkerTemplate("ts", newWorkerType);
511
+
512
+ await mkdir(path.join(creationDirectory, "./src"), {
513
+ recursive: true,
514
+ });
515
+
516
+ await writeFile(
517
+ path.join(creationDirectory, "./src/index.ts"),
518
+ readFileSync(path.join(getBasePath(), `templates/${template}`))
519
+ );
520
+
521
+ logger.log(
522
+ `✨ Created ${path.relative(
523
+ process.cwd(),
524
+ path.join(creationDirectory, "./src/index.ts")
525
+ )}`
526
+ );
527
+
528
+ shouldCreateTests =
529
+ yesFlag ||
530
+ (await confirm(
531
+ "Would you like us to write your first test with Vitest?"
532
+ ));
533
+
534
+ if (shouldCreateTests) {
535
+ if (yesFlag) {
536
+ logger.info("Your project will use Vitest to run your tests.");
537
+ }
538
+
539
+ newWorkerTestType = "vitest";
540
+ devDepsToInstall.push(newWorkerTestType);
541
+
542
+ await writeFile(
543
+ path.join(creationDirectory, "./src/index.test.ts"),
544
+ readFileSync(
545
+ path.join(
546
+ getBasePath(),
547
+ `templates/init-tests/test-${newWorkerTestType}-new-worker.ts`
548
+ )
549
+ )
550
+ );
551
+ logger.log(
552
+ `✨ Created ${path.relative(
553
+ process.cwd(),
554
+ path.join(creationDirectory, "./src/index.test.ts")
555
+ )}`
556
+ );
557
+ }
558
+
559
+ await writePackageJsonScriptsAndUpdateWranglerToml({
560
+ isWritingScripts: shouldWritePackageJsonScripts,
561
+ isAddingTests: shouldCreateTests,
562
+ isCreatingWranglerToml: justCreatedWranglerToml,
563
+ packagePath: pathToPackageJson,
564
+ testRunner: newWorkerTestType,
565
+ scriptPath: "src/index.ts",
566
+ extraToml: getNewWorkerToml(newWorkerType),
567
+ });
568
+ }
569
+ }
570
+ }
571
+ } else {
572
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
573
+ const newWorkerFilename = path.relative(
574
+ process.cwd(),
575
+ path.join(creationDirectory, "./src/index.js")
576
+ );
577
+
578
+ if (fromDashScriptName) {
579
+ logger.warn(
580
+ "After running `wrangler init --from-dash`, modifying your worker via the Cloudflare dashboard is discouraged.\nEdits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish."
581
+ );
582
+
583
+ await mkdir(path.join(creationDirectory, "./src"), {
584
+ recursive: true,
585
+ });
586
+
587
+ const defaultEnvironment =
588
+ serviceMetadata?.default_environment.environment;
589
+
590
+ // I want the default environment, assuming it's the most up to date code.
591
+ const dashScript = await fetchDashboardScript(
592
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
593
+ );
594
+
595
+ await writeFile(
596
+ path.join(creationDirectory, "./src/index.js"),
597
+ dashScript
598
+ );
599
+
600
+ await writePackageJsonScriptsAndUpdateWranglerToml({
601
+ isWritingScripts: shouldWritePackageJsonScripts,
602
+ isCreatingWranglerToml: justCreatedWranglerToml,
603
+ packagePath: pathToPackageJson,
604
+ scriptPath: "src/index.js",
605
+ //? Should we have Environment argument for `wrangler init --from-dash` - Jacob
606
+ extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
607
+ defaultEnvironment,
608
+ environments: serviceMetadata?.environments,
609
+ })) as TOML.JsonMap,
610
+ });
611
+ } else {
612
+ const newWorkerType = yesFlag
613
+ ? "fetch"
614
+ : await getNewWorkerType(newWorkerFilename);
615
+
616
+ if (newWorkerType !== "none") {
617
+ const template = getNewWorkerTemplate("js", newWorkerType);
618
+
619
+ await mkdir(path.join(creationDirectory, "./src"), {
620
+ recursive: true,
621
+ });
622
+ await writeFile(
623
+ path.join(creationDirectory, "./src/index.js"),
624
+ readFileSync(path.join(getBasePath(), `templates/${template}`))
625
+ );
626
+
627
+ logger.log(
628
+ `✨ Created ${path.relative(
629
+ process.cwd(),
630
+ path.join(creationDirectory, "./src/index.js")
631
+ )}`
632
+ );
633
+
634
+ shouldCreateTests =
635
+ yesFlag ||
636
+ (await confirm("Would you like us to write your first test?"));
637
+
638
+ if (shouldCreateTests) {
639
+ newWorkerTestType = await getNewWorkerTestType(yesFlag);
640
+ devDepsToInstall.push(newWorkerTestType);
641
+ await writeFile(
642
+ path.join(creationDirectory, "./src/index.test.js"),
643
+ readFileSync(
644
+ path.join(
645
+ getBasePath(),
646
+ `templates/init-tests/test-${newWorkerTestType}-new-worker.js`
647
+ )
648
+ )
649
+ );
650
+ logger.log(
651
+ `✨ Created ${path.relative(
652
+ process.cwd(),
653
+ path.join(creationDirectory, "./src/index.test.js")
654
+ )}`
655
+ );
656
+ }
657
+
658
+ await writePackageJsonScriptsAndUpdateWranglerToml({
659
+ isWritingScripts: shouldWritePackageJsonScripts,
660
+ isAddingTests: shouldCreateTests,
661
+ testRunner: newWorkerTestType,
662
+ isCreatingWranglerToml: justCreatedWranglerToml,
663
+ packagePath: pathToPackageJson,
664
+ scriptPath: "src/index.js",
665
+ extraToml: getNewWorkerToml(newWorkerType),
666
+ });
667
+ }
668
+ }
669
+ }
670
+ }
671
+ // install packages as the final step of init
672
+ try {
673
+ await installPackages(
674
+ shouldRunPackageManagerInstall,
675
+ devDepsToInstall,
676
+ packageManager
677
+ );
678
+ } catch (e) {
679
+ // fetching packages could fail due to loss of internet, etc
680
+ // we should let folks know we failed to fetch, but their
681
+ // workers project is still ready to go
682
+ logger.error(e instanceof Error ? e.message : e);
683
+ instructions.push(
684
+ "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
685
+ );
686
+ }
687
+
688
+ // let users know what to do now
689
+ instructions.forEach((instruction) => logger.log(instruction));
690
+ }
691
+
692
+ /*
693
+ * Passes the array of accumulated devDeps to install through to
694
+ * the package manager. Also generates a human-readable list
695
+ * of packages it installed.
696
+ * If there are no devDeps to install, optionally runs
697
+ * the package manager's install command.
698
+ */
699
+ async function installPackages(
700
+ shouldRunInstall: boolean,
701
+ depsToInstall: string[],
702
+ packageManager: PackageManager
703
+ ) {
704
+ //lets install the devDeps they asked for
705
+ //and run their package manager's install command if needed
706
+ if (depsToInstall.length > 0) {
707
+ const formatter = new Intl.ListFormat("en", {
708
+ style: "long",
709
+ type: "conjunction",
710
+ });
711
+ await packageManager.addDevDeps(...depsToInstall);
712
+ const versionlessPackages = depsToInstall.map((dep) =>
713
+ dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
714
+ );
715
+
716
+ logger.log(
717
+ `✨ Installed ${formatter.format(
718
+ versionlessPackages
719
+ )} into devDependencies`
720
+ );
721
+ } else {
722
+ if (shouldRunInstall) {
723
+ await packageManager.install();
724
+ }
725
+ }
726
+ }
727
+
728
+ async function getNewWorkerType(newWorkerFilename: string) {
729
+ return select(`Would you like to create a Worker at ${newWorkerFilename}?`, {
730
+ choices: [
731
+ {
732
+ value: "none",
733
+ title: "None",
734
+ },
735
+ {
736
+ value: "fetch",
737
+ title: "Fetch handler",
738
+ },
739
+ {
740
+ value: "scheduled",
741
+ title: "Scheduled handler",
742
+ },
743
+ ],
744
+ defaultOption: 1,
745
+ });
746
+ }
747
+
748
+ async function getNewWorkerTestType(yesFlag?: boolean) {
749
+ return yesFlag
750
+ ? "jest"
751
+ : select(`Which test runner would you like to use?`, {
752
+ choices: [
753
+ {
754
+ value: "vitest",
755
+ title: "Vitest",
756
+ },
757
+ {
758
+ value: "jest",
759
+ title: "Jest",
760
+ },
761
+ ],
762
+ defaultOption: 1,
763
+ });
764
+ }
765
+
766
+ function getNewWorkerTemplate(
767
+ lang: "js" | "ts",
768
+ workerType: "fetch" | "scheduled"
769
+ ) {
770
+ const templates = {
771
+ "js-fetch": "new-worker.js",
772
+ "js-scheduled": "new-worker-scheduled.js",
773
+ "ts-fetch": "new-worker.ts",
774
+ "ts-scheduled": "new-worker-scheduled.ts",
775
+ };
776
+
777
+ return templates[`${lang}-${workerType}`];
778
+ }
779
+
780
+ function getNewWorkerToml(workerType: "fetch" | "scheduled"): TOML.JsonMap {
781
+ if (workerType === "scheduled") {
782
+ return {
783
+ triggers: {
784
+ crons: ["1 * * * *"],
785
+ },
786
+ };
787
+ }
788
+
789
+ return {};
790
+ }
791
+
792
+ /**
793
+ * Find the path to the given `basename` file from the `cwd`.
794
+ *
795
+ * If `isolatedInit` is true then we only look in the `cwd` directory for the file.
796
+ * Otherwise we also search up the tree.
797
+ */
798
+ async function findPath(
799
+ isolatedInit: boolean,
800
+ cwd: string,
801
+ basename: string
802
+ ): Promise<string | undefined> {
803
+ if (isolatedInit) {
804
+ return fs.existsSync(path.resolve(cwd, basename))
805
+ ? path.resolve(cwd, basename)
806
+ : undefined;
807
+ } else {
808
+ return await findUp(basename, {
809
+ cwd: cwd,
810
+ });
811
+ }
812
+ }
813
+
814
+ async function getWorkerConfig(
815
+ accountId: string,
816
+ fromDashScriptName: string,
817
+ {
818
+ defaultEnvironment,
819
+ environments,
820
+ }: {
821
+ defaultEnvironment: string | undefined;
822
+ environments: ServiceMetadataRes["environments"] | undefined;
823
+ }
824
+ ): Promise<RawConfig> {
825
+ const [bindings, routes, serviceEnvMetadata, cronTriggers] =
826
+ await Promise.all([
827
+ fetchResult<WorkerMetadata["bindings"]>(
828
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/bindings`
829
+ ),
830
+ fetchResult<RoutesRes>(
831
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/routes`
832
+ ),
833
+ fetchResult<ServiceMetadataRes["default_environment"]>(
834
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}`
835
+ ),
836
+ fetchResult<CronTriggersRes>(
837
+ `/accounts/${accountId}/workers/scripts/${fromDashScriptName}/schedules`
838
+ ),
839
+ ]).catch((e) => {
840
+ throw new Error(
841
+ `Error Occurred ${e}: Unable to fetch bindings, routes, or services metadata from the dashboard. Please try again later.`
842
+ );
843
+ });
844
+
845
+ const mappedBindings = mapBindings(bindings);
846
+
847
+ const durableObjectClassNames = bindings
848
+ .filter((binding) => binding.type === "durable_object_namespace")
849
+ .map(
850
+ (durableObject) => (durableObject as { class_name: string }).class_name
851
+ );
852
+
853
+ const routeOrRoutes = routes.map((rawRoute) => {
854
+ const { id: _id, ...route } = rawRoute;
855
+ if (Object.keys(route).length === 1) {
856
+ return route.pattern;
857
+ } else {
858
+ return route as Route;
859
+ }
860
+ });
861
+ const routeOrRoutesToConfig =
862
+ routeOrRoutes.length > 1
863
+ ? { routes: routeOrRoutes }
864
+ : { route: routeOrRoutes[0] };
865
+
866
+ return {
867
+ compatibility_date:
868
+ serviceEnvMetadata.script.compatibility_date ??
869
+ new Date().toISOString().substring(0, 10),
870
+ ...routeOrRoutesToConfig,
871
+ usage_model: serviceEnvMetadata.script.usage_model,
872
+ placement:
873
+ serviceEnvMetadata.script.placement_mode === "smart"
874
+ ? { mode: "smart" }
875
+ : undefined,
876
+ ...(durableObjectClassNames.length
877
+ ? {
878
+ migrations: [
879
+ {
880
+ tag: serviceEnvMetadata.script.migration_tag,
881
+ new_classes: durableObjectClassNames,
882
+ },
883
+ ],
884
+ }
885
+ : {}),
886
+ triggers: {
887
+ crons: cronTriggers.schedules.map((scheduled) => scheduled.cron),
888
+ },
889
+ env: environments
890
+ ?.filter((env) => env.environment !== "production")
891
+ // `env` can have multiple Environments, with different configs.
892
+ .reduce((envObj, { environment }) => {
893
+ return { ...envObj, [environment]: {} };
894
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
895
+ }, {} as RawConfig["env"]),
896
+ ...mappedBindings,
897
+ };
898
+ }
899
+
900
+ export function mapBindings(bindings: WorkerMetadataBinding[]): RawConfig {
901
+ return (
902
+ bindings
903
+ .filter((binding) => (binding.type as string) !== "secret_text")
904
+ // Combine the same types into {[type]: [binding]}
905
+ .reduce((configObj, binding) => {
906
+ // Some types have different names in wrangler.toml
907
+ // I want the type safety of the binding being destructured after the case narrowing the union but type is unused
908
+
909
+ switch (binding.type) {
910
+ case "plain_text":
911
+ {
912
+ configObj.vars = {
913
+ ...(configObj.vars ?? {}),
914
+ [binding.name]: binding.text,
915
+ };
916
+ }
917
+ break;
918
+ case "json":
919
+ {
920
+ configObj.vars = {
921
+ ...(configObj.vars ?? {}),
922
+ name: binding.name,
923
+ json: binding.json,
924
+ };
925
+ }
926
+ break;
927
+ case "kv_namespace":
928
+ {
929
+ configObj.kv_namespaces = [
930
+ ...(configObj.kv_namespaces ?? []),
931
+ { id: binding.namespace_id, binding: binding.name },
932
+ ];
933
+ }
934
+ break;
935
+ case "durable_object_namespace":
936
+ {
937
+ configObj.durable_objects = {
938
+ bindings: [
939
+ ...(configObj.durable_objects?.bindings ?? []),
940
+ {
941
+ name: binding.name,
942
+ class_name: binding.class_name,
943
+ script_name: binding.script_name,
944
+ environment: binding.environment,
945
+ },
946
+ ],
947
+ };
948
+ }
949
+ break;
950
+ case "r2_bucket":
951
+ {
952
+ configObj.r2_buckets = [
953
+ ...(configObj.r2_buckets ?? []),
954
+ { binding: binding.name, bucket_name: binding.bucket_name },
955
+ ];
956
+ }
957
+ break;
958
+ case "service":
959
+ {
960
+ configObj.services = [
961
+ ...(configObj.services ?? []),
962
+ {
963
+ binding: binding.name,
964
+ service: binding.service,
965
+ environment: binding.environment,
966
+ },
967
+ ];
968
+ }
969
+ break;
970
+ case "analytics_engine":
971
+ {
972
+ configObj.analytics_engine_datasets = [
973
+ ...(configObj.analytics_engine_datasets ?? []),
974
+ { binding: binding.name, dataset: binding.dataset },
975
+ ];
976
+ }
977
+ break;
978
+ case "dispatch_namespace":
979
+ {
980
+ configObj.dispatch_namespaces = [
981
+ ...(configObj.dispatch_namespaces ?? []),
982
+ { binding: binding.name, namespace: binding.namespace },
983
+ ];
984
+ }
985
+ break;
986
+ case "logfwdr":
987
+ {
988
+ configObj.logfwdr = {
989
+ // TODO: Messaging about adding schema file path
990
+ schema: "",
991
+ bindings: [
992
+ ...(configObj.logfwdr?.bindings ?? []),
993
+ { name: binding.name, destination: binding.destination },
994
+ ],
995
+ };
996
+ }
997
+ break;
998
+ case "wasm_module":
999
+ {
1000
+ configObj.wasm_modules = {
1001
+ ...(configObj.wasm_modules ?? {}),
1002
+ [binding.name]: binding.part,
1003
+ };
1004
+ }
1005
+ break;
1006
+ case "text_blob":
1007
+ {
1008
+ configObj.text_blobs = {
1009
+ ...(configObj.text_blobs ?? {}),
1010
+ [binding.name]: binding.part,
1011
+ };
1012
+ }
1013
+ break;
1014
+ case "data_blob":
1015
+ {
1016
+ configObj.data_blobs = {
1017
+ ...(configObj.data_blobs ?? {}),
1018
+ [binding.name]: binding.part,
1019
+ };
1020
+ }
1021
+ break;
1022
+ default: {
1023
+ // If we don't know what the type is, its an unsafe binding
1024
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1025
+ if (!(binding as any)?.type) break;
1026
+ configObj.unsafe = {
1027
+ bindings: [...(configObj.unsafe?.bindings ?? []), binding],
1028
+ metadata: configObj.unsafe?.metadata ?? undefined,
1029
+ };
1030
+ }
1031
+ }
1032
+
1033
+ return configObj;
1034
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1035
+ }, {} as RawConfig)
1036
+ );
1037
+ }