wrangler 0.0.0-e7cf0caa → 0.0.0-e7ea6005c

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