wrangler 0.0.0-e6c71262 → 0.0.0-e6ddf8a7

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