wrangler 0.0.0-e322475 → 0.0.0-e33294b0

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 (324) hide show
  1. package/README.md +24 -4
  2. package/bin/wrangler.js +170 -62
  3. package/miniflare-dist/index.mjs +1499 -34
  4. package/package.json +193 -156
  5. package/src/__tests__/access.test.ts +25 -0
  6. package/src/__tests__/api-dev.test.ts +238 -0
  7. package/src/__tests__/api-devregistry.test.js +64 -0
  8. package/src/__tests__/api.test.ts +80 -0
  9. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  10. package/src/__tests__/config-cache.test.ts +30 -24
  11. package/src/__tests__/configuration.test.ts +4222 -3537
  12. package/src/__tests__/d1/d1.test.ts +82 -0
  13. package/src/__tests__/d1/execute.test.ts +64 -0
  14. package/src/__tests__/d1/migrate.test.ts +155 -0
  15. package/src/__tests__/d1/splitter.test.ts +255 -0
  16. package/src/__tests__/delete.test.ts +266 -0
  17. package/src/__tests__/deployments.test.ts +129 -0
  18. package/src/__tests__/dev.test.tsx +1560 -1028
  19. package/src/__tests__/generate.test.ts +238 -0
  20. package/src/__tests__/get-host-from-url.test.ts +16 -0
  21. package/src/__tests__/guess-worker-format.test.ts +68 -68
  22. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  23. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  24. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  25. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  26. package/src/__tests__/helpers/mock-bin.ts +20 -20
  27. package/src/__tests__/helpers/mock-console.ts +51 -42
  28. package/src/__tests__/helpers/mock-dialogs.ts +88 -102
  29. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  30. package/src/__tests__/helpers/mock-get-zone-from-host.ts +11 -0
  31. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  32. package/src/__tests__/helpers/mock-istty.ts +65 -18
  33. package/src/__tests__/helpers/mock-known-routes.ts +12 -0
  34. package/src/__tests__/helpers/mock-kv.ts +41 -28
  35. package/src/__tests__/helpers/mock-oauth-flow.ts +241 -233
  36. package/src/__tests__/helpers/mock-process.ts +23 -13
  37. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  38. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  39. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  40. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  41. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  42. package/src/__tests__/helpers/msw/handlers/deployments.ts +93 -0
  43. package/src/__tests__/helpers/msw/handlers/namespaces.ts +81 -0
  44. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  45. package/src/__tests__/helpers/msw/handlers/r2.ts +60 -0
  46. package/src/__tests__/helpers/msw/handlers/script.ts +56 -0
  47. package/src/__tests__/helpers/msw/handlers/user.ts +52 -0
  48. package/src/__tests__/helpers/msw/handlers/zones.ts +20 -0
  49. package/src/__tests__/helpers/msw/index.ts +50 -0
  50. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  51. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  52. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  53. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  54. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  55. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  56. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  57. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  58. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  59. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  60. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  61. package/src/__tests__/https-options.test.ts +142 -109
  62. package/src/__tests__/index.test.ts +254 -238
  63. package/src/__tests__/init.test.ts +3097 -1925
  64. package/src/__tests__/jest.setup.ts +143 -75
  65. package/src/__tests__/kv.test.ts +1788 -1509
  66. package/src/__tests__/logger.test.ts +96 -96
  67. package/src/__tests__/logout.test.ts +47 -0
  68. package/src/__tests__/metrics.test.ts +493 -0
  69. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  70. package/src/__tests__/middleware.test.ts +815 -0
  71. package/src/__tests__/mtls-certificates.test.ts +585 -0
  72. package/src/__tests__/package-manager.test.ts +303 -303
  73. package/src/__tests__/pages/deployment-list.test.ts +78 -0
  74. package/src/__tests__/pages/functions-build.test.ts +402 -0
  75. package/src/__tests__/pages/pages.test.ts +81 -0
  76. package/src/__tests__/pages/project-create.test.ts +63 -0
  77. package/src/__tests__/pages/project-list.test.ts +108 -0
  78. package/src/__tests__/pages/project-upload.test.ts +481 -0
  79. package/src/__tests__/pages/publish.test.ts +2745 -0
  80. package/src/__tests__/pages-deployment-tail.test.ts +955 -0
  81. package/src/__tests__/parse.test.ts +358 -252
  82. package/src/__tests__/paths.test.ts +39 -0
  83. package/src/__tests__/publish.test.ts +8002 -6010
  84. package/src/__tests__/pubsub.test.ts +493 -0
  85. package/src/__tests__/queues.test.ts +529 -0
  86. package/src/__tests__/r2.test.ts +369 -228
  87. package/src/__tests__/route.test.ts +18 -18
  88. package/src/__tests__/secret.test.ts +681 -469
  89. package/src/__tests__/tail.test.ts +835 -567
  90. package/src/__tests__/test-old-node-version.js +31 -0
  91. package/src/__tests__/tsconfig-sanity.ts +12 -0
  92. package/src/__tests__/tsconfig.json +8 -0
  93. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  94. package/src/__tests__/type-generation.test.ts +233 -0
  95. package/src/__tests__/user.test.ts +107 -121
  96. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  97. package/src/__tests__/validate-dev-props.test.ts +56 -0
  98. package/src/__tests__/version.test.ts +35 -0
  99. package/src/__tests__/whoami.test.tsx +165 -132
  100. package/src/__tests__/worker-namespace.test.ts +339 -0
  101. package/src/abort.d.ts +1 -1
  102. package/src/api/dev.ts +328 -0
  103. package/src/api/index.ts +11 -0
  104. package/src/api/mtls-certificate.ts +148 -0
  105. package/src/api/pages/create-worker-bundle-contents.ts +75 -0
  106. package/src/api/pages/index.ts +5 -0
  107. package/src/api/pages/publish.tsx +368 -0
  108. package/src/bundle-reporter.ts +68 -0
  109. package/src/bundle.ts +839 -167
  110. package/src/cfetch/index.ts +120 -83
  111. package/src/cfetch/internal.ts +208 -92
  112. package/src/cli.ts +23 -8
  113. package/src/config/config.ts +244 -205
  114. package/src/config/diagnostics.ts +61 -61
  115. package/src/config/environment.ts +523 -357
  116. package/src/config/index.ts +346 -196
  117. package/src/config/validation-helpers.ts +379 -366
  118. package/src/config/validation.ts +2020 -1402
  119. package/src/config-cache.ts +81 -41
  120. package/src/create-worker-preview.ts +239 -142
  121. package/src/create-worker-upload-form.ts +318 -238
  122. package/src/d1/backups.tsx +215 -0
  123. package/src/d1/constants.ts +2 -0
  124. package/src/d1/create.tsx +64 -0
  125. package/src/d1/delete.ts +53 -0
  126. package/src/d1/execute.tsx +354 -0
  127. package/src/d1/formatTimeAgo.ts +14 -0
  128. package/src/d1/index.ts +100 -0
  129. package/src/d1/list.tsx +60 -0
  130. package/src/d1/migrations/apply.tsx +206 -0
  131. package/src/d1/migrations/create.tsx +76 -0
  132. package/src/d1/migrations/helpers.ts +172 -0
  133. package/src/d1/migrations/index.ts +3 -0
  134. package/src/d1/migrations/list.tsx +92 -0
  135. package/src/d1/migrations/options.ts +23 -0
  136. package/src/d1/options.ts +22 -0
  137. package/src/d1/splitter.ts +161 -0
  138. package/src/d1/types.ts +25 -0
  139. package/src/d1/utils.ts +49 -0
  140. package/src/delete.ts +100 -0
  141. package/src/deployments.ts +116 -0
  142. package/src/deprecated/index.ts +144 -0
  143. package/src/dev/dev-vars.ts +20 -17
  144. package/src/dev/dev.tsx +530 -329
  145. package/src/dev/get-local-persistence-path.ts +31 -0
  146. package/src/dev/local.tsx +903 -301
  147. package/src/dev/remote.tsx +619 -236
  148. package/src/dev/start-server.ts +538 -0
  149. package/src/dev/use-esbuild.ts +184 -91
  150. package/src/dev/validate-dev-props.ts +31 -0
  151. package/src/dev-registry.ts +201 -0
  152. package/src/dev.tsx +914 -0
  153. package/src/dialogs.ts +136 -0
  154. package/src/dispatch-namespace.ts +211 -0
  155. package/src/docs/index.ts +97 -0
  156. package/src/durable.ts +87 -87
  157. package/src/entry.ts +236 -236
  158. package/src/environment-variables/factory.ts +88 -0
  159. package/src/environment-variables/misc-variables.ts +30 -0
  160. package/src/errors.ts +6 -6
  161. package/src/generate/index.ts +298 -0
  162. package/src/git-client.ts +112 -19
  163. package/src/global-wrangler-config-path.ts +26 -0
  164. package/src/https-options.ts +84 -80
  165. package/src/index.ts +705 -0
  166. package/src/init.ts +1022 -0
  167. package/src/inspect.ts +698 -593
  168. package/src/intl-polyfill.d.ts +123 -123
  169. package/src/is-ci.ts +14 -0
  170. package/src/is-interactive.ts +16 -0
  171. package/src/jest.d.ts +4 -0
  172. package/src/kv/helpers.ts +430 -0
  173. package/src/kv/index.ts +594 -0
  174. package/src/logger.ts +77 -46
  175. package/src/metrics/index.ts +5 -0
  176. package/src/metrics/metrics-config.ts +239 -0
  177. package/src/metrics/metrics-dispatcher.ts +96 -0
  178. package/src/metrics/metrics-usage-headers.ts +24 -0
  179. package/src/metrics/send-event.ts +98 -0
  180. package/src/miniflare-cli/assets.ts +250 -0
  181. package/src/miniflare-cli/index.ts +202 -33
  182. package/src/miniflare-cli/request-context.ts +18 -18
  183. package/src/miniflare-cli/tsconfig.json +9 -0
  184. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  185. package/src/miniflare-cli/types.ts +11 -0
  186. package/src/module-collection.ts +221 -212
  187. package/src/mtls-certificate/cli.ts +155 -0
  188. package/src/open-in-browser.ts +4 -4
  189. package/src/package-manager.ts +173 -128
  190. package/src/pages/build.ts +232 -0
  191. package/src/pages/buildFunctions.ts +130 -0
  192. package/src/pages/constants.ts +18 -0
  193. package/src/pages/deployment-tails.ts +281 -0
  194. package/src/pages/deployments.tsx +86 -0
  195. package/src/pages/dev.ts +716 -0
  196. package/src/pages/errors.ts +66 -0
  197. package/src/pages/functions/buildPlugin.ts +90 -0
  198. package/src/pages/functions/buildWorker.ts +288 -0
  199. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  200. package/src/pages/functions/filepath-routing.ts +189 -0
  201. package/src/pages/functions/identifiers.ts +78 -0
  202. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  203. package/src/pages/functions/routes-consolidation.ts +73 -0
  204. package/src/pages/functions/routes-transformation.test.ts +282 -0
  205. package/src/pages/functions/routes-transformation.ts +115 -0
  206. package/src/pages/functions/routes-validation.test.ts +403 -0
  207. package/src/pages/functions/routes-validation.ts +202 -0
  208. package/src/pages/functions/routes.ts +151 -0
  209. package/src/pages/functions/tsconfig.json +8 -0
  210. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  211. package/src/pages/functions.ts +86 -0
  212. package/src/pages/hash.ts +13 -0
  213. package/src/pages/index.ts +102 -0
  214. package/src/pages/projects.tsx +162 -0
  215. package/src/pages/prompt-select-project.tsx +31 -0
  216. package/src/pages/publish.tsx +276 -0
  217. package/src/pages/types.ts +46 -0
  218. package/src/pages/upload.tsx +449 -0
  219. package/src/pages/utils.ts +23 -0
  220. package/src/parse.ts +225 -139
  221. package/src/paths.ts +53 -8
  222. package/src/proxy.ts +623 -405
  223. package/src/publish/index.ts +274 -0
  224. package/src/publish/publish.ts +1065 -0
  225. package/src/pubsub/index.ts +286 -0
  226. package/src/pubsub/pubsub-commands.ts +623 -0
  227. package/src/queues/cli/commands/consumer/add.ts +65 -0
  228. package/src/queues/cli/commands/consumer/index.ts +19 -0
  229. package/src/queues/cli/commands/consumer/remove.ts +31 -0
  230. package/src/queues/cli/commands/create.ts +25 -0
  231. package/src/queues/cli/commands/delete.ts +26 -0
  232. package/src/queues/cli/commands/index.ts +35 -0
  233. package/src/queues/cli/commands/list.ts +25 -0
  234. package/src/queues/client.ts +135 -0
  235. package/src/queues/utils.ts +18 -0
  236. package/src/r2/constants.ts +4 -0
  237. package/src/r2/helpers.ts +131 -0
  238. package/src/r2/index.ts +289 -0
  239. package/src/routes.ts +140 -0
  240. package/src/secret/index.ts +375 -0
  241. package/src/selfsigned.d.ts +23 -23
  242. package/src/sites.ts +372 -0
  243. package/src/tail/createTail.ts +406 -0
  244. package/src/tail/filters.ts +109 -111
  245. package/src/tail/index.ts +208 -296
  246. package/src/tail/printing.ts +101 -46
  247. package/src/tsconfig-sanity.ts +16 -0
  248. package/src/type-generation.ts +181 -0
  249. package/src/update-check.ts +11 -11
  250. package/src/user/access.ts +68 -0
  251. package/src/user/auth-variables.ts +113 -0
  252. package/src/user/choose-account.tsx +39 -0
  253. package/src/user/generate-auth-url.ts +33 -0
  254. package/src/user/generate-random-state.ts +16 -0
  255. package/src/user/index.ts +2 -0
  256. package/src/user/user.ts +1233 -0
  257. package/src/utils/collectKeyValues.ts +14 -0
  258. package/src/whoami.ts +135 -0
  259. package/src/worker.ts +183 -107
  260. package/src/yargs-types.ts +37 -0
  261. package/src/zones.ts +158 -40
  262. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  263. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  264. package/templates/__tests__/tsconfig.json +8 -0
  265. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  266. package/templates/checked-fetch.js +23 -0
  267. package/templates/d1-beta-facade.js +241 -0
  268. package/templates/facade.d.ts +14 -0
  269. package/templates/first-party-worker-module-facade.ts +19 -0
  270. package/templates/format-dev-errors.ts +34 -0
  271. package/templates/init-tests/test-jest-new-worker.js +23 -0
  272. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  273. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  274. package/templates/middleware/common.ts +62 -0
  275. package/templates/middleware/loader-modules.ts +84 -0
  276. package/templates/middleware/loader-sw.ts +233 -0
  277. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  278. package/templates/middleware/middleware-pretty-error.ts +40 -0
  279. package/templates/middleware/middleware-scheduled.ts +15 -0
  280. package/templates/new-worker-scheduled.js +3 -3
  281. package/templates/new-worker-scheduled.ts +15 -15
  282. package/templates/new-worker.js +3 -3
  283. package/templates/new-worker.ts +18 -15
  284. package/templates/no-op-worker.js +8 -8
  285. package/templates/pages-dev-pipeline.ts +31 -0
  286. package/templates/pages-dev-util.ts +52 -0
  287. package/templates/pages-shim.ts +12 -0
  288. package/templates/pages-template-plugin.ts +176 -0
  289. package/templates/pages-template-worker.ts +189 -0
  290. package/templates/serve-static-assets.ts +66 -0
  291. package/templates/service-bindings-module-facade.js +55 -0
  292. package/templates/service-bindings-sw-facade.js +42 -0
  293. package/templates/tsconfig-sanity.ts +11 -0
  294. package/templates/tsconfig.init.json +106 -0
  295. package/templates/tsconfig.json +6 -103
  296. package/templates/tsconfig.tsbuildinfo +1 -0
  297. package/wrangler-dist/cli.d.ts +1108 -0
  298. package/wrangler-dist/cli.js +131192 -112380
  299. package/wrangler-dist/wasm-sync.wasm +0 -0
  300. package/pages/functions/buildPlugin.ts +0 -105
  301. package/pages/functions/buildWorker.ts +0 -151
  302. package/pages/functions/filepath-routing.ts +0 -189
  303. package/pages/functions/identifiers.ts +0 -78
  304. package/pages/functions/routes.ts +0 -156
  305. package/pages/functions/template-plugin.ts +0 -147
  306. package/pages/functions/template-worker.ts +0 -143
  307. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  308. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  309. package/src/__tests__/pages.test.ts +0 -754
  310. package/src/bundle-reporter.tsx +0 -29
  311. package/src/dialogs.tsx +0 -135
  312. package/src/environment-variables.ts +0 -35
  313. package/src/generate-auth-url.ts +0 -33
  314. package/src/generate-random-state.ts +0 -16
  315. package/src/index.tsx +0 -2896
  316. package/src/kv.ts +0 -408
  317. package/src/miniflare-cli/enum-keys.ts +0 -17
  318. package/src/pages.tsx +0 -2093
  319. package/src/publish.ts +0 -739
  320. package/src/r2.ts +0 -50
  321. package/src/sites.tsx +0 -368
  322. package/src/user.tsx +0 -1202
  323. package/src/whoami.tsx +0 -71
  324. package/templates/static-asset-facade.js +0 -43
@@ -2,36 +2,36 @@ import path from "node:path";
2
2
  import TOML from "@iarna/toml";
3
3
  import { Diagnostics } from "./diagnostics";
4
4
  import {
5
- deprecated,
6
- experimental,
7
- hasProperty,
8
- inheritable,
9
- isBoolean,
10
- isObjectWith,
11
- isOneOf,
12
- isOptionalProperty,
13
- isRequiredProperty,
14
- isString,
15
- isStringArray,
16
- validateAdditionalProperties,
17
- notInheritable,
18
- validateOptionalProperty,
19
- validateOptionalTypedArray,
20
- validateRequiredProperty,
21
- validateTypedArray,
22
- all,
23
- isMutuallyExclusiveWith,
24
- inheritableInLegacyEnvironments,
25
- appendEnvName,
26
- getBindingNames,
27
- isValidName,
5
+ deprecated,
6
+ experimental,
7
+ hasProperty,
8
+ inheritable,
9
+ isBoolean,
10
+ isObjectWith,
11
+ isOneOf,
12
+ isOptionalProperty,
13
+ isRequiredProperty,
14
+ isString,
15
+ isStringArray,
16
+ validateAdditionalProperties,
17
+ notInheritable,
18
+ validateOptionalProperty,
19
+ validateOptionalTypedArray,
20
+ validateRequiredProperty,
21
+ validateTypedArray,
22
+ all,
23
+ isMutuallyExclusiveWith,
24
+ inheritableInLegacyEnvironments,
25
+ appendEnvName,
26
+ getBindingNames,
27
+ isValidName,
28
28
  } from "./validation-helpers";
29
29
  import type { Config, DevConfig, RawConfig, RawDevConfig } from "./config";
30
30
  import type {
31
- RawEnvironment,
32
- DeprecatedUpload,
33
- Environment,
34
- Rule,
31
+ RawEnvironment,
32
+ DeprecatedUpload,
33
+ Environment,
34
+ Rule,
35
35
  } from "./environment";
36
36
  import type { ValidatorFn } from "./validation-helpers";
37
37
 
@@ -46,590 +46,659 @@ const ENGLISH = new Intl.ListFormat("en");
46
46
  * Any errors or warnings from the validation are available in the returned `diagnostics` object.
47
47
  */
48
48
  export function normalizeAndValidateConfig(
49
- rawConfig: RawConfig,
50
- configPath: string | undefined,
51
- args: unknown
49
+ rawConfig: RawConfig,
50
+ configPath: string | undefined,
51
+ args: unknown
52
52
  ): {
53
- config: Config;
54
- diagnostics: Diagnostics;
53
+ config: Config;
54
+ diagnostics: Diagnostics;
55
55
  } {
56
- const diagnostics = new Diagnostics(
57
- `Processing ${
58
- configPath ? path.relative(process.cwd(), configPath) : "wrangler"
59
- } configuration:`
60
- );
61
-
62
- deprecated(
63
- diagnostics,
64
- rawConfig,
65
- "miniflare",
66
- "Wrangler does not use configuration in the `miniflare` section. Unless you are using Miniflare directly you can remove this section.",
67
- true,
68
- "😶 Ignored"
69
- );
70
-
71
- deprecated(
72
- diagnostics,
73
- rawConfig,
74
- "type",
75
- "Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
76
- true,
77
- "😶 Ignored"
78
- );
79
-
80
- deprecated(
81
- diagnostics,
82
- rawConfig,
83
- "webpack_config",
84
- "Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
85
- true,
86
- "😶 Ignored"
87
- );
88
-
89
- validateOptionalProperty(
90
- diagnostics,
91
- "",
92
- "legacy_env",
93
- rawConfig.legacy_env,
94
- "boolean"
95
- );
96
-
97
- // TODO: set the default to false to turn on service environments as the default
98
- const isLegacyEnv =
99
- (args as { "legacy-env": boolean | undefined })["legacy-env"] ??
100
- rawConfig.legacy_env ??
101
- true;
102
-
103
- // TODO: remove this once service environments goes GA.
104
- if (!isLegacyEnv) {
105
- diagnostics.warnings.push(
106
- "Experimental: Service environments are in beta, and their behaviour is guaranteed to change in the future. DO NOT USE IN PRODUCTION."
107
- );
108
- }
109
-
110
- const topLevelEnv = normalizeAndValidateEnvironment(
111
- diagnostics,
112
- configPath,
113
- rawConfig
114
- );
115
-
116
- //TODO: find a better way to define the type of Args that can be passed to the normalizeAndValidateConfig()
117
- const envName = (args as { env: string | undefined }).env;
118
-
119
- let activeEnv = topLevelEnv;
120
- if (envName !== undefined) {
121
- const envDiagnostics = new Diagnostics(
122
- `"env.${envName}" environment configuration`
123
- );
124
- const rawEnv = rawConfig.env?.[envName];
125
- if (rawEnv !== undefined) {
126
- activeEnv = normalizeAndValidateEnvironment(
127
- envDiagnostics,
128
- configPath,
129
- rawEnv,
130
- envName,
131
- topLevelEnv,
132
- isLegacyEnv,
133
- rawConfig
134
- );
135
- diagnostics.addChild(envDiagnostics);
136
- } else {
137
- // An environment was specified, but no configuration for it was found.
138
- // To cover any legacy environment cases, where the `envName` is used,
139
- // Let's create a fake active environment with the specified `envName`.
140
- activeEnv = normalizeAndValidateEnvironment(
141
- envDiagnostics,
142
- configPath,
143
- {},
144
- envName,
145
- topLevelEnv,
146
- isLegacyEnv,
147
- rawConfig
148
- );
149
- const envNames = rawConfig.env
150
- ? `The available configured environment names are: ${JSON.stringify(
151
- Object.keys(rawConfig.env)
152
- )}\n`
153
- : "";
154
- const message =
155
- `No environment found in configuration with name "${envName}".\n` +
156
- `Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.\n` +
157
- `${envNames}\n` +
158
- `Consider adding an environment configuration section to the wrangler.toml file:\n` +
159
- "```\n[env." +
160
- envName +
161
- "]\n```\n";
162
-
163
- if (envNames.length > 0) {
164
- diagnostics.errors.push(message);
165
- } else {
166
- // Only warn (rather than error) if there are not actually any environments configured in wrangler.toml.
167
- diagnostics.warnings.push(message);
168
- }
169
- }
170
- }
171
-
172
- // Process the top-level default environment configuration.
173
- const config: Config = {
174
- configPath,
175
- legacy_env: isLegacyEnv,
176
- ...activeEnv,
177
- dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
178
- migrations: normalizeAndValidateMigrations(
179
- diagnostics,
180
- rawConfig.migrations ?? [],
181
- activeEnv.durable_objects
182
- ),
183
- site: normalizeAndValidateSite(
184
- diagnostics,
185
- configPath,
186
- rawConfig,
187
- activeEnv.main
188
- ),
189
- assets: normalizeAndValidateAssets(diagnostics, configPath, rawConfig),
190
- wasm_modules: normalizeAndValidateModulePaths(
191
- diagnostics,
192
- configPath,
193
- "wasm_modules",
194
- rawConfig.wasm_modules
195
- ),
196
- text_blobs: normalizeAndValidateModulePaths(
197
- diagnostics,
198
- configPath,
199
- "text_blobs",
200
- rawConfig.text_blobs
201
- ),
202
- data_blobs: normalizeAndValidateModulePaths(
203
- diagnostics,
204
- configPath,
205
- "data_blobs",
206
- rawConfig.data_blobs
207
- ),
208
- };
209
-
210
- validateBindingsHaveUniqueNames(diagnostics, config);
211
-
212
- validateAdditionalProperties(
213
- diagnostics,
214
- "top-level",
215
- Object.keys(rawConfig),
216
- [...Object.keys(config), "env"]
217
- );
218
-
219
- experimental(diagnostics, rawConfig, "assets");
220
-
221
- return { config, diagnostics };
56
+ const diagnostics = new Diagnostics(
57
+ `Processing ${
58
+ configPath ? path.relative(process.cwd(), configPath) : "wrangler"
59
+ } configuration:`
60
+ );
61
+
62
+ deprecated(
63
+ diagnostics,
64
+ rawConfig,
65
+ "miniflare",
66
+ "Wrangler does not use configuration in the `miniflare` section. Unless you are using Miniflare directly you can remove this section.",
67
+ true,
68
+ "😶 Ignored"
69
+ );
70
+
71
+ deprecated(
72
+ diagnostics,
73
+ rawConfig,
74
+ "type",
75
+ "Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
76
+ true,
77
+ "😶 Ignored"
78
+ );
79
+
80
+ deprecated(
81
+ diagnostics,
82
+ rawConfig,
83
+ "webpack_config",
84
+ "Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
85
+ true,
86
+ "😶 Ignored"
87
+ );
88
+
89
+ validateOptionalProperty(
90
+ diagnostics,
91
+ "",
92
+ "legacy_env",
93
+ rawConfig.legacy_env,
94
+ "boolean"
95
+ );
96
+
97
+ validateOptionalProperty(
98
+ diagnostics,
99
+ "",
100
+ "send_metrics",
101
+ rawConfig.send_metrics,
102
+ "boolean"
103
+ );
104
+
105
+ validateOptionalProperty(
106
+ diagnostics,
107
+ "",
108
+ "keep_vars",
109
+ rawConfig.keep_vars,
110
+ "boolean"
111
+ );
112
+
113
+ // TODO: set the default to false to turn on service environments as the default
114
+ const isLegacyEnv =
115
+ (args as { "legacy-env": boolean | undefined })["legacy-env"] ??
116
+ rawConfig.legacy_env ??
117
+ true;
118
+
119
+ // TODO: remove this once service environments goes GA.
120
+ if (!isLegacyEnv) {
121
+ diagnostics.warnings.push(
122
+ "Experimental: Service environments are in beta, and their behaviour is guaranteed to change in the future. DO NOT USE IN PRODUCTION."
123
+ );
124
+ }
125
+
126
+ const topLevelEnv = normalizeAndValidateEnvironment(
127
+ diagnostics,
128
+ configPath,
129
+ rawConfig
130
+ );
131
+
132
+ //TODO: find a better way to define the type of Args that can be passed to the normalizeAndValidateConfig()
133
+ const envName = (args as { env: string | undefined }).env;
134
+
135
+ let activeEnv = topLevelEnv;
136
+ if (envName !== undefined) {
137
+ const envDiagnostics = new Diagnostics(
138
+ `"env.${envName}" environment configuration`
139
+ );
140
+ const rawEnv = rawConfig.env?.[envName];
141
+ if (rawEnv !== undefined) {
142
+ activeEnv = normalizeAndValidateEnvironment(
143
+ envDiagnostics,
144
+ configPath,
145
+ rawEnv,
146
+ envName,
147
+ topLevelEnv,
148
+ isLegacyEnv,
149
+ rawConfig
150
+ );
151
+ diagnostics.addChild(envDiagnostics);
152
+ } else {
153
+ // An environment was specified, but no configuration for it was found.
154
+ // To cover any legacy environment cases, where the `envName` is used,
155
+ // Let's create a fake active environment with the specified `envName`.
156
+ activeEnv = normalizeAndValidateEnvironment(
157
+ envDiagnostics,
158
+ configPath,
159
+ {},
160
+ envName,
161
+ topLevelEnv,
162
+ isLegacyEnv,
163
+ rawConfig
164
+ );
165
+ const envNames = rawConfig.env
166
+ ? `The available configured environment names are: ${JSON.stringify(
167
+ Object.keys(rawConfig.env)
168
+ )}\n`
169
+ : "";
170
+ const message =
171
+ `No environment found in configuration with name "${envName}".\n` +
172
+ `Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.\n` +
173
+ `${envNames}\n` +
174
+ `Consider adding an environment configuration section to the wrangler.toml file:\n` +
175
+ "```\n[env." +
176
+ envName +
177
+ "]\n```\n";
178
+
179
+ if (envNames.length > 0) {
180
+ diagnostics.errors.push(message);
181
+ } else {
182
+ // Only warn (rather than error) if there are not actually any environments configured in wrangler.toml.
183
+ diagnostics.warnings.push(message);
184
+ }
185
+ }
186
+ }
187
+
188
+ // Process the top-level default environment configuration.
189
+ const config: Config = {
190
+ configPath,
191
+ legacy_env: isLegacyEnv,
192
+ send_metrics: rawConfig.send_metrics,
193
+ keep_vars: rawConfig.keep_vars,
194
+ ...activeEnv,
195
+ dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
196
+ migrations: normalizeAndValidateMigrations(
197
+ diagnostics,
198
+ rawConfig.migrations ?? [],
199
+ activeEnv.durable_objects
200
+ ),
201
+ site: normalizeAndValidateSite(
202
+ diagnostics,
203
+ configPath,
204
+ rawConfig,
205
+ activeEnv.main
206
+ ),
207
+ assets: normalizeAndValidateAssets(diagnostics, configPath, rawConfig),
208
+ wasm_modules: normalizeAndValidateModulePaths(
209
+ diagnostics,
210
+ configPath,
211
+ "wasm_modules",
212
+ rawConfig.wasm_modules
213
+ ),
214
+ text_blobs: normalizeAndValidateModulePaths(
215
+ diagnostics,
216
+ configPath,
217
+ "text_blobs",
218
+ rawConfig.text_blobs
219
+ ),
220
+ data_blobs: normalizeAndValidateModulePaths(
221
+ diagnostics,
222
+ configPath,
223
+ "data_blobs",
224
+ rawConfig.data_blobs
225
+ ),
226
+ };
227
+
228
+ validateBindingsHaveUniqueNames(diagnostics, config);
229
+
230
+ validateAdditionalProperties(
231
+ diagnostics,
232
+ "top-level",
233
+ Object.keys(rawConfig),
234
+ [...Object.keys(config), "env"]
235
+ );
236
+
237
+ experimental(diagnostics, rawConfig, "assets");
238
+
239
+ return { config, diagnostics };
222
240
  }
223
241
 
224
242
  /**
225
243
  * Validate the `build` configuration and return the normalized values.
226
244
  */
227
245
  function normalizeAndValidateBuild(
228
- diagnostics: Diagnostics,
229
- rawEnv: RawEnvironment,
230
- rawBuild: Config["build"],
231
- configPath: string | undefined
246
+ diagnostics: Diagnostics,
247
+ rawEnv: RawEnvironment,
248
+ rawBuild: Config["build"],
249
+ configPath: string | undefined
232
250
  ): Config["build"] & { deprecatedUpload: DeprecatedUpload } {
233
- const { command, cwd, watch_dir = "./src", upload, ...rest } = rawBuild;
234
- const deprecatedUpload: DeprecatedUpload = { ...upload };
235
- validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
236
-
237
- validateOptionalProperty(diagnostics, "build", "command", command, "string");
238
- validateOptionalProperty(diagnostics, "build", "cwd", cwd, "string");
239
- if (Array.isArray(watch_dir)) {
240
- validateTypedArray(diagnostics, "build.watch_dir", watch_dir, "string");
241
- } else {
242
- validateOptionalProperty(
243
- diagnostics,
244
- "build",
245
- "watch_dir",
246
- watch_dir,
247
- "string"
248
- );
249
- }
250
-
251
- deprecated(
252
- diagnostics,
253
- rawEnv,
254
- "build.upload.format",
255
- "The format is inferred automatically from the code.",
256
- true
257
- );
258
-
259
- if (rawEnv.main !== undefined && rawBuild.upload?.main) {
260
- diagnostics.errors.push(
261
- `Don't define both the \`main\` and \`build.upload.main\` fields in your configuration.\n` +
262
- `They serve the same purpose: to point to the entry-point of your worker.\n` +
263
- `Delete the \`build.upload.main\` and \`build.upload.dir\` field from your config.`
264
- );
265
- } else {
266
- deprecated(
267
- diagnostics,
268
- rawEnv,
269
- "build.upload.main",
270
- `Delete the \`build.upload.main\` and \`build.upload.dir\` fields.\n` +
271
- `Then add the top level \`main\` field to your configuration file:\n` +
272
- `\`\`\`\n` +
273
- `main = "${path.join(
274
- rawBuild.upload?.dir ?? "./dist",
275
- rawBuild.upload?.main ?? "."
276
- )}"\n` +
277
- `\`\`\``,
278
- true
279
- );
280
-
281
- deprecated(
282
- diagnostics,
283
- rawEnv,
284
- "build.upload.dir",
285
- `Use the top level "main" field or a command-line argument to specify the entry-point for the Worker.`,
286
- true
287
- );
288
- }
289
-
290
- return {
291
- command,
292
- watch_dir:
293
- // - `watch_dir` only matters when `command` is defined, so we apply
294
- // a default only when `command` is defined
295
- // - `configPath` will always be defined since `build` can only
296
- // be configured in `wrangler.toml`, but who knows, that may
297
- // change in the future, so we do a check anyway
298
- command && configPath
299
- ? Array.isArray(watch_dir)
300
- ? watch_dir.map((dir) =>
301
- path.relative(
302
- process.cwd(),
303
- path.join(path.dirname(configPath), `${dir}`)
304
- )
305
- )
306
- : path.relative(
307
- process.cwd(),
308
- path.join(path.dirname(configPath), `${watch_dir}`)
309
- )
310
- : watch_dir,
311
- cwd,
312
- deprecatedUpload,
313
- };
251
+ const { command, cwd, watch_dir = "./src", upload, ...rest } = rawBuild;
252
+ const deprecatedUpload: DeprecatedUpload = { ...upload };
253
+ validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
254
+
255
+ validateOptionalProperty(diagnostics, "build", "command", command, "string");
256
+ validateOptionalProperty(diagnostics, "build", "cwd", cwd, "string");
257
+ if (Array.isArray(watch_dir)) {
258
+ validateTypedArray(diagnostics, "build.watch_dir", watch_dir, "string");
259
+ } else {
260
+ validateOptionalProperty(
261
+ diagnostics,
262
+ "build",
263
+ "watch_dir",
264
+ watch_dir,
265
+ "string"
266
+ );
267
+ }
268
+
269
+ deprecated(
270
+ diagnostics,
271
+ rawEnv,
272
+ "build.upload.format",
273
+ "The format is inferred automatically from the code.",
274
+ true
275
+ );
276
+
277
+ if (rawEnv.main !== undefined && rawBuild.upload?.main) {
278
+ diagnostics.errors.push(
279
+ `Don't define both the \`main\` and \`build.upload.main\` fields in your configuration.\n` +
280
+ `They serve the same purpose: to point to the entry-point of your worker.\n` +
281
+ `Delete the \`build.upload.main\` and \`build.upload.dir\` field from your config.`
282
+ );
283
+ } else {
284
+ deprecated(
285
+ diagnostics,
286
+ rawEnv,
287
+ "build.upload.main",
288
+ `Delete the \`build.upload.main\` and \`build.upload.dir\` fields.\n` +
289
+ `Then add the top level \`main\` field to your configuration file:\n` +
290
+ `\`\`\`\n` +
291
+ `main = "${path.join(
292
+ rawBuild.upload?.dir ?? "./dist",
293
+ rawBuild.upload?.main ?? "."
294
+ )}"\n` +
295
+ `\`\`\``,
296
+ true
297
+ );
298
+
299
+ deprecated(
300
+ diagnostics,
301
+ rawEnv,
302
+ "build.upload.dir",
303
+ `Use the top level "main" field or a command-line argument to specify the entry-point for the Worker.`,
304
+ true
305
+ );
306
+ }
307
+
308
+ return {
309
+ command,
310
+ watch_dir:
311
+ // - `watch_dir` only matters when `command` is defined, so we apply
312
+ // a default only when `command` is defined
313
+ // - `configPath` will always be defined since `build` can only
314
+ // be configured in `wrangler.toml`, but who knows, that may
315
+ // change in the future, so we do a check anyway
316
+ command && configPath
317
+ ? Array.isArray(watch_dir)
318
+ ? watch_dir.map((dir) =>
319
+ path.relative(
320
+ process.cwd(),
321
+ path.join(path.dirname(configPath), `${dir}`)
322
+ )
323
+ )
324
+ : path.relative(
325
+ process.cwd(),
326
+ path.join(path.dirname(configPath), `${watch_dir}`)
327
+ )
328
+ : watch_dir,
329
+ cwd,
330
+ deprecatedUpload,
331
+ };
314
332
  }
315
333
 
316
334
  /**
317
335
  * Validate the `main` field and return the normalized values.
318
336
  */
319
337
  function normalizeAndValidateMainField(
320
- configPath: string | undefined,
321
- rawMain: string | undefined,
322
- deprecatedUpload: DeprecatedUpload | undefined
338
+ configPath: string | undefined,
339
+ rawMain: string | undefined,
340
+ deprecatedUpload: DeprecatedUpload | undefined
323
341
  ): string | undefined {
324
- const configDir = path.dirname(configPath ?? "wrangler.toml");
325
- if (rawMain !== undefined) {
326
- if (typeof rawMain === "string") {
327
- const directory = path.resolve(configDir);
328
- return path.resolve(directory, rawMain);
329
- } else {
330
- return rawMain;
331
- }
332
- } else if (deprecatedUpload?.main !== undefined) {
333
- const directory = path.resolve(
334
- configDir,
335
- deprecatedUpload?.dir || "./dist"
336
- );
337
- return path.resolve(directory, deprecatedUpload.main);
338
- } else {
339
- return;
340
- }
342
+ const configDir = path.dirname(configPath ?? "wrangler.toml");
343
+ if (rawMain !== undefined) {
344
+ if (typeof rawMain === "string") {
345
+ const directory = path.resolve(configDir);
346
+ return path.resolve(directory, rawMain);
347
+ } else {
348
+ return rawMain;
349
+ }
350
+ } else if (deprecatedUpload?.main !== undefined) {
351
+ const directory = path.resolve(
352
+ configDir,
353
+ deprecatedUpload?.dir || "./dist"
354
+ );
355
+ return path.resolve(directory, deprecatedUpload.main);
356
+ } else {
357
+ return;
358
+ }
341
359
  }
342
360
 
343
361
  /**
344
362
  * Validate the `dev` configuration and return the normalized values.
345
363
  */
346
364
  function normalizeAndValidateDev(
347
- diagnostics: Diagnostics,
348
- rawDev: RawDevConfig
365
+ diagnostics: Diagnostics,
366
+ rawDev: RawDevConfig
349
367
  ): DevConfig {
350
- const {
351
- ip = "localhost",
352
- port,
353
- local_protocol = "http",
354
- upstream_protocol = "https",
355
- host,
356
- ...rest
357
- } = rawDev;
358
- validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
359
-
360
- validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
361
- validateOptionalProperty(diagnostics, "dev", "port", port, "number");
362
- validateOptionalProperty(
363
- diagnostics,
364
- "dev",
365
- "local_protocol",
366
- local_protocol,
367
- "string",
368
- ["http", "https"]
369
- );
370
- validateOptionalProperty(
371
- diagnostics,
372
- "dev",
373
- "upstream_protocol",
374
- upstream_protocol,
375
- "string",
376
- ["http", "https"]
377
- );
378
- validateOptionalProperty(diagnostics, "dev", "host", host, "string");
379
- return { ip, port, local_protocol, upstream_protocol, host };
368
+ const {
369
+ ip = "0.0.0.0",
370
+ port,
371
+ inspector_port,
372
+ local_protocol = "http",
373
+ upstream_protocol = "https",
374
+ host,
375
+ ...rest
376
+ } = rawDev;
377
+ validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
378
+
379
+ validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
380
+ validateOptionalProperty(diagnostics, "dev", "port", port, "number");
381
+ validateOptionalProperty(
382
+ diagnostics,
383
+ "dev",
384
+ "inspector_port",
385
+ inspector_port,
386
+ "number"
387
+ );
388
+ validateOptionalProperty(
389
+ diagnostics,
390
+ "dev",
391
+ "local_protocol",
392
+ local_protocol,
393
+ "string",
394
+ ["http", "https"]
395
+ );
396
+ validateOptionalProperty(
397
+ diagnostics,
398
+ "dev",
399
+ "upstream_protocol",
400
+ upstream_protocol,
401
+ "string",
402
+ ["http", "https"]
403
+ );
404
+ validateOptionalProperty(diagnostics, "dev", "host", host, "string");
405
+ return { ip, port, inspector_port, local_protocol, upstream_protocol, host };
380
406
  }
381
407
 
382
408
  /**
383
409
  * Validate the `migrations` configuration and return the normalized values.
384
410
  */
385
411
  function normalizeAndValidateMigrations(
386
- diagnostics: Diagnostics,
387
- rawMigrations: Config["migrations"],
388
- durableObjects: Config["durable_objects"]
412
+ diagnostics: Diagnostics,
413
+ rawMigrations: Config["migrations"],
414
+ durableObjects: Config["durable_objects"]
389
415
  ): Config["migrations"] {
390
- if (!Array.isArray(rawMigrations)) {
391
- diagnostics.errors.push(
392
- `The optional "migrations" field should be an array, but got ${JSON.stringify(
393
- rawMigrations
394
- )}`
395
- );
396
- return [];
397
- } else {
398
- for (let i = 0; i < rawMigrations.length; i++) {
399
- const { tag, new_classes, renamed_classes, deleted_classes, ...rest } =
400
- rawMigrations[i];
401
-
402
- validateAdditionalProperties(
403
- diagnostics,
404
- "migrations",
405
- Object.keys(rest),
406
- []
407
- );
408
-
409
- validateRequiredProperty(
410
- diagnostics,
411
- `migrations[${i}]`,
412
- `tag`,
413
- tag,
414
- "string"
415
- );
416
- validateOptionalTypedArray(
417
- diagnostics,
418
- `migrations[${i}].new_classes`,
419
- new_classes,
420
- "string"
421
- );
422
- if (renamed_classes !== undefined) {
423
- if (!Array.isArray(renamed_classes)) {
424
- diagnostics.errors.push(
425
- `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
426
- renamed_classes
427
- )}.`
428
- );
429
- } else if (
430
- renamed_classes.some(
431
- (c) =>
432
- typeof c !== "object" ||
433
- !isRequiredProperty(c, "from", "string") ||
434
- !isRequiredProperty(c, "to", "string")
435
- )
436
- ) {
437
- diagnostics.errors.push(
438
- `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
439
- renamed_classes
440
- )}.`
441
- );
442
- }
443
- }
444
- validateOptionalTypedArray(
445
- diagnostics,
446
- `migrations[${i}].deleted_classes`,
447
- deleted_classes,
448
- "string"
449
- );
450
- }
451
-
452
- if (
453
- Array.isArray(durableObjects?.bindings) &&
454
- durableObjects.bindings.length > 0
455
- ) {
456
- // intrinsic [durable_objects] implies [migrations]
457
- const exportedDurableObjects = (durableObjects.bindings || []).filter(
458
- (binding) => !binding.script_name
459
- );
460
- if (exportedDurableObjects.length > 0 && rawMigrations.length === 0) {
461
- if (
462
- !exportedDurableObjects.some(
463
- (exportedDurableObject) =>
464
- typeof exportedDurableObject.class_name !== "string"
465
- )
466
- ) {
467
- const durableObjectClassnames = exportedDurableObjects.map(
468
- (durable) => durable.class_name
469
- );
470
-
471
- diagnostics.warnings.push(
472
- `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${durableObjectClassnames.join(
473
- ", "
474
- )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Add this configuration to your wrangler.toml:
416
+ if (!Array.isArray(rawMigrations)) {
417
+ diagnostics.errors.push(
418
+ `The optional "migrations" field should be an array, but got ${JSON.stringify(
419
+ rawMigrations
420
+ )}`
421
+ );
422
+ return [];
423
+ } else {
424
+ for (let i = 0; i < rawMigrations.length; i++) {
425
+ const { tag, new_classes, renamed_classes, deleted_classes, ...rest } =
426
+ rawMigrations[i];
427
+
428
+ validateAdditionalProperties(
429
+ diagnostics,
430
+ "migrations",
431
+ Object.keys(rest),
432
+ []
433
+ );
434
+
435
+ validateRequiredProperty(
436
+ diagnostics,
437
+ `migrations[${i}]`,
438
+ `tag`,
439
+ tag,
440
+ "string"
441
+ );
442
+ validateOptionalTypedArray(
443
+ diagnostics,
444
+ `migrations[${i}].new_classes`,
445
+ new_classes,
446
+ "string"
447
+ );
448
+ if (renamed_classes !== undefined) {
449
+ if (!Array.isArray(renamed_classes)) {
450
+ diagnostics.errors.push(
451
+ `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
452
+ renamed_classes
453
+ )}.`
454
+ );
455
+ } else if (
456
+ renamed_classes.some(
457
+ (c) =>
458
+ typeof c !== "object" ||
459
+ !isRequiredProperty(c, "from", "string") ||
460
+ !isRequiredProperty(c, "to", "string")
461
+ )
462
+ ) {
463
+ diagnostics.errors.push(
464
+ `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
465
+ renamed_classes
466
+ )}.`
467
+ );
468
+ }
469
+ }
470
+ validateOptionalTypedArray(
471
+ diagnostics,
472
+ `migrations[${i}].deleted_classes`,
473
+ deleted_classes,
474
+ "string"
475
+ );
476
+ }
477
+
478
+ if (
479
+ Array.isArray(durableObjects?.bindings) &&
480
+ durableObjects.bindings.length > 0
481
+ ) {
482
+ // intrinsic [durable_objects] implies [migrations]
483
+ const exportedDurableObjects = (durableObjects.bindings || []).filter(
484
+ (binding) => !binding.script_name
485
+ );
486
+ if (exportedDurableObjects.length > 0 && rawMigrations.length === 0) {
487
+ if (
488
+ !exportedDurableObjects.some(
489
+ (exportedDurableObject) =>
490
+ typeof exportedDurableObject.class_name !== "string"
491
+ )
492
+ ) {
493
+ const durableObjectClassnames = exportedDurableObjects.map(
494
+ (durable) => durable.class_name
495
+ );
496
+
497
+ diagnostics.warnings.push(
498
+ `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${durableObjectClassnames.join(
499
+ ", "
500
+ )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Add this configuration to your wrangler.toml:
475
501
 
476
502
  \`\`\`
477
503
  [[migrations]]
478
504
  tag = "v1" # Should be unique for each entry
479
505
  new_classes = [${durableObjectClassnames
480
- .map((name) => `"${name}"`)
481
- .join(", ")}]
506
+ .map((name) => `"${name}"`)
507
+ .join(", ")}]
482
508
  \`\`\`
483
509
 
484
510
  Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
485
- );
486
- }
487
- }
488
- }
511
+ );
512
+ }
513
+ }
514
+ }
489
515
 
490
- return rawMigrations;
491
- }
516
+ return rawMigrations;
517
+ }
492
518
  }
493
519
 
494
520
  /**
495
521
  * Validate the `site` configuration and return the normalized values.
496
522
  */
497
523
  function normalizeAndValidateSite(
498
- diagnostics: Diagnostics,
499
- configPath: string | undefined,
500
- rawConfig: RawConfig,
501
- mainEntryPoint: string | undefined
524
+ diagnostics: Diagnostics,
525
+ configPath: string | undefined,
526
+ rawConfig: RawConfig,
527
+ mainEntryPoint: string | undefined
502
528
  ): Config["site"] {
503
- if (rawConfig?.site !== undefined) {
504
- const { bucket, include = [], exclude = [], ...rest } = rawConfig.site;
505
-
506
- validateAdditionalProperties(diagnostics, "site", Object.keys(rest), [
507
- "entry-point",
508
- ]);
509
- validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
510
- validateTypedArray(diagnostics, "sites.include", include, "string");
511
- validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
512
- validateOptionalProperty(
513
- diagnostics,
514
- "site",
515
- "entry-point",
516
- rawConfig.site["entry-point"],
517
- "string"
518
- );
519
-
520
- deprecated(
521
- diagnostics,
522
- rawConfig,
523
- `site.entry-point`,
524
- `Delete the \`site.entry-point\` field, then add the top level \`main\` field to your configuration file:\n` +
525
- `\`\`\`\n` +
526
- `main = "${path.join(
527
- String(rawConfig.site["entry-point"]) || "workers-site",
528
- path.extname(String(rawConfig.site["entry-point"]) || "workers-site")
529
- ? ""
530
- : "index.js"
531
- )}"\n` +
532
- `\`\`\``,
533
- false,
534
- undefined,
535
- "warning"
536
- );
537
-
538
- let siteEntryPoint = rawConfig.site["entry-point"];
539
-
540
- if (!mainEntryPoint && !siteEntryPoint) {
541
- // this means that we're defaulting to "workers-site"
542
- // so let's add the deprecation warning
543
- diagnostics.warnings.push(
544
- `Because you've defined a [site] configuration, we're defaulting to "workers-site" for the deprecated \`site.entry-point\`field.\n` +
545
- `Add the top level \`main\` field to your configuration file:\n` +
546
- `\`\`\`\n` +
547
- `main = "workers-site/index.js"\n` +
548
- `\`\`\``
549
- );
550
- siteEntryPoint = "workers-site";
551
- } else if (mainEntryPoint && siteEntryPoint) {
552
- diagnostics.errors.push(
553
- `Don't define both the \`main\` and \`site.entry-point\` fields in your configuration.\n` +
554
- `They serve the same purpose: to point to the entry-point of your worker.\n` +
555
- `Delete the deprecated \`site.entry-point\` field from your config.`
556
- );
557
- }
558
-
559
- if (configPath && siteEntryPoint) {
560
- // rewrite the path to be relative to the working directory
561
- siteEntryPoint = path.relative(
562
- process.cwd(),
563
- path.join(path.dirname(configPath), siteEntryPoint)
564
- );
565
- }
566
-
567
- return {
568
- bucket,
569
- "entry-point": siteEntryPoint,
570
- include,
571
- exclude,
572
- };
573
- }
574
- return undefined;
529
+ if (rawConfig?.site !== undefined) {
530
+ const { bucket, include = [], exclude = [], ...rest } = rawConfig.site;
531
+
532
+ validateAdditionalProperties(diagnostics, "site", Object.keys(rest), [
533
+ "entry-point",
534
+ ]);
535
+ validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
536
+ validateTypedArray(diagnostics, "sites.include", include, "string");
537
+ validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
538
+ validateOptionalProperty(
539
+ diagnostics,
540
+ "site",
541
+ "entry-point",
542
+ rawConfig.site["entry-point"],
543
+ "string"
544
+ );
545
+
546
+ deprecated(
547
+ diagnostics,
548
+ rawConfig,
549
+ `site.entry-point`,
550
+ `Delete the \`site.entry-point\` field, then add the top level \`main\` field to your configuration file:\n` +
551
+ `\`\`\`\n` +
552
+ `main = "${path.join(
553
+ String(rawConfig.site["entry-point"]) || "workers-site",
554
+ path.extname(String(rawConfig.site["entry-point"]) || "workers-site")
555
+ ? ""
556
+ : "index.js"
557
+ )}"\n` +
558
+ `\`\`\``,
559
+ false,
560
+ undefined,
561
+ "warning"
562
+ );
563
+
564
+ let siteEntryPoint = rawConfig.site["entry-point"];
565
+
566
+ if (!mainEntryPoint && !siteEntryPoint) {
567
+ // this means that we're defaulting to "workers-site"
568
+ // so let's add the deprecation warning
569
+ diagnostics.warnings.push(
570
+ `Because you've defined a [site] configuration, we're defaulting to "workers-site" for the deprecated \`site.entry-point\`field.\n` +
571
+ `Add the top level \`main\` field to your configuration file:\n` +
572
+ `\`\`\`\n` +
573
+ `main = "workers-site/index.js"\n` +
574
+ `\`\`\``
575
+ );
576
+ siteEntryPoint = "workers-site";
577
+ } else if (mainEntryPoint && siteEntryPoint) {
578
+ diagnostics.errors.push(
579
+ `Don't define both the \`main\` and \`site.entry-point\` fields in your configuration.\n` +
580
+ `They serve the same purpose: to point to the entry-point of your worker.\n` +
581
+ `Delete the deprecated \`site.entry-point\` field from your config.`
582
+ );
583
+ }
584
+
585
+ if (configPath && siteEntryPoint) {
586
+ // rewrite the path to be relative to the working directory
587
+ siteEntryPoint = path.relative(
588
+ process.cwd(),
589
+ path.join(path.dirname(configPath), siteEntryPoint)
590
+ );
591
+ }
592
+
593
+ return {
594
+ bucket,
595
+ "entry-point": siteEntryPoint,
596
+ include,
597
+ exclude,
598
+ };
599
+ }
600
+ return undefined;
575
601
  }
576
602
 
577
603
  /**
578
604
  * Validate the `assets` configuration and return normalized values.
579
605
  */
580
606
  function normalizeAndValidateAssets(
581
- diagnostics: Diagnostics,
582
- configPath: string | undefined,
583
- rawConfig: RawConfig
584
- ) {
585
- if (
586
- typeof rawConfig?.assets === "string" ||
587
- rawConfig?.assets === undefined
588
- ) {
589
- return rawConfig?.assets;
590
- }
591
-
592
- const { bucket, include = [], exclude = [], ...rest } = rawConfig.assets;
593
-
594
- validateAdditionalProperties(diagnostics, "assets", Object.keys(rest), []);
595
- validateRequiredProperty(diagnostics, "assets", "bucket", bucket, "string");
596
- validateTypedArray(diagnostics, "assets.include", include, "string");
597
- validateTypedArray(diagnostics, "assets.exclude", exclude, "string");
598
-
599
- return {
600
- bucket,
601
- include,
602
- exclude,
603
- };
607
+ diagnostics: Diagnostics,
608
+ configPath: string | undefined,
609
+ rawConfig: RawConfig
610
+ ): Config["assets"] {
611
+ // Even though the type doesn't say it,
612
+ // we allow for a string input in the config,
613
+ // so let's normalise it
614
+ if (typeof rawConfig?.assets === "string") {
615
+ return {
616
+ bucket: rawConfig.assets,
617
+ include: [],
618
+ exclude: [],
619
+ browser_TTL: undefined,
620
+ serve_single_page_app: false,
621
+ };
622
+ }
623
+
624
+ if (rawConfig?.assets === undefined) {
625
+ return undefined;
626
+ }
627
+
628
+ if (typeof rawConfig.assets !== "object") {
629
+ diagnostics.errors.push(
630
+ `Expected the \`assets\` field to be a string or an object, but got ${typeof rawConfig.assets}.`
631
+ );
632
+ return undefined;
633
+ }
634
+
635
+ const {
636
+ bucket,
637
+ include = [],
638
+ exclude = [],
639
+ browser_TTL,
640
+ serve_single_page_app,
641
+ ...rest
642
+ } = rawConfig.assets;
643
+
644
+ validateAdditionalProperties(diagnostics, "assets", Object.keys(rest), []);
645
+
646
+ validateRequiredProperty(diagnostics, "assets", "bucket", bucket, "string");
647
+ validateTypedArray(diagnostics, "assets.include", include, "string");
648
+ validateTypedArray(diagnostics, "assets.exclude", exclude, "string");
649
+
650
+ validateOptionalProperty(
651
+ diagnostics,
652
+ "assets",
653
+ "browser_TTL",
654
+ browser_TTL,
655
+ "number"
656
+ );
657
+
658
+ validateOptionalProperty(
659
+ diagnostics,
660
+ "assets",
661
+ "serve_single_page_app",
662
+ serve_single_page_app,
663
+ "boolean"
664
+ );
665
+
666
+ return {
667
+ bucket,
668
+ include,
669
+ exclude,
670
+ browser_TTL,
671
+ serve_single_page_app,
672
+ };
604
673
  }
605
674
 
606
675
  /**
607
676
  * Map the paths of the `wasm_modules`, `text_blobs` or `data_blobs` configuration to be relative to the current working directory.
608
677
  */
609
678
  function normalizeAndValidateModulePaths(
610
- diagnostics: Diagnostics,
611
- configPath: string | undefined,
612
- field: "wasm_modules" | "text_blobs" | "data_blobs",
613
- rawMapping: Record<string, string> | undefined
679
+ diagnostics: Diagnostics,
680
+ configPath: string | undefined,
681
+ field: "wasm_modules" | "text_blobs" | "data_blobs",
682
+ rawMapping: Record<string, string> | undefined
614
683
  ): Record<string, string> | undefined {
615
- if (rawMapping === undefined) {
616
- return undefined;
617
- }
618
- const mapping: Record<string, string> = {};
619
- // Rewrite paths to be relative to the cwd, rather than the config path.
620
- for (const [name, filePath] of Object.entries(rawMapping)) {
621
- if (isString(diagnostics, `${field}['${name}']`, filePath, undefined)) {
622
- if (configPath) {
623
- mapping[name] = configPath
624
- ? path.relative(
625
- process.cwd(),
626
- path.join(path.dirname(configPath), filePath)
627
- )
628
- : filePath;
629
- }
630
- }
631
- }
632
- return mapping;
684
+ if (rawMapping === undefined) {
685
+ return undefined;
686
+ }
687
+ const mapping: Record<string, string> = {};
688
+ // Rewrite paths to be relative to the cwd, rather than the config path.
689
+ for (const [name, filePath] of Object.entries(rawMapping)) {
690
+ if (isString(diagnostics, `${field}['${name}']`, filePath, undefined)) {
691
+ if (configPath) {
692
+ mapping[name] = configPath
693
+ ? path.relative(
694
+ process.cwd(),
695
+ path.join(path.dirname(configPath), filePath)
696
+ )
697
+ : filePath;
698
+ }
699
+ }
700
+ }
701
+ return mapping;
633
702
  }
634
703
 
635
704
  /**
@@ -637,638 +706,866 @@ function normalizeAndValidateModulePaths(
637
706
  * or an object that looks like {pattern: string, zone_id: string }
638
707
  */
639
708
  function isValidRouteValue(item: unknown): boolean {
640
- if (!item) {
641
- return false;
642
- }
643
- if (typeof item === "string") {
644
- return true;
645
- }
646
- if (typeof item === "object") {
647
- if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
648
- return false;
649
- }
650
-
651
- const otherKeys = Object.keys(item).length - 1; // minus one to subtract "pattern"
652
-
653
- const hasZoneId =
654
- hasProperty(item, "zone_id") && typeof item.zone_id === "string";
655
- const hasZoneName =
656
- hasProperty(item, "zone_name") && typeof item.zone_name === "string";
657
- const hasCustomDomainFlag =
658
- hasProperty(item, "custom_domain") &&
659
- typeof item.custom_domain === "boolean";
660
-
661
- if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
662
- return true;
663
- } else if (
664
- otherKeys === 1 &&
665
- (hasZoneId || hasZoneName || hasCustomDomainFlag)
666
- ) {
667
- return true;
668
- }
669
- }
670
- return false;
709
+ if (!item) {
710
+ return false;
711
+ }
712
+ if (typeof item === "string") {
713
+ return true;
714
+ }
715
+ if (typeof item === "object") {
716
+ if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
717
+ return false;
718
+ }
719
+
720
+ const otherKeys = Object.keys(item).length - 1; // minus one to subtract "pattern"
721
+
722
+ const hasZoneId =
723
+ hasProperty(item, "zone_id") && typeof item.zone_id === "string";
724
+ const hasZoneName =
725
+ hasProperty(item, "zone_name") && typeof item.zone_name === "string";
726
+ const hasCustomDomainFlag =
727
+ hasProperty(item, "custom_domain") &&
728
+ typeof item.custom_domain === "boolean";
729
+
730
+ if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
731
+ return true;
732
+ } else if (
733
+ otherKeys === 1 &&
734
+ (hasZoneId || hasZoneName || hasCustomDomainFlag)
735
+ ) {
736
+ return true;
737
+ }
738
+ }
739
+ return false;
740
+ }
741
+
742
+ /**
743
+ * If account_id has been passed as an empty string, normalise it to undefined.
744
+ * This is to workaround older Wrangler v1-era templates that have account_id = '',
745
+ * which isn't a valid value anyway
746
+ */
747
+ function mutateEmptyStringAccountIDValue(
748
+ diagnostics: Diagnostics,
749
+ rawEnv: RawEnvironment
750
+ ) {
751
+ if (rawEnv.account_id === "") {
752
+ diagnostics.warnings.push(
753
+ `The "account_id" field in your configuration is an empty string and will be ignored.\n` +
754
+ `Please remove the "account_id" field from your configuration.`
755
+ );
756
+ rawEnv.account_id = undefined;
757
+ }
758
+ return rawEnv;
759
+ }
760
+
761
+ /**
762
+ * Normalize empty string to `undefined` by mutating rawEnv.route value.
763
+ * As part of backward compatibility with Wrangler v1 converting empty string to `undefined`
764
+ */
765
+ function mutateEmptyStringRouteValue(
766
+ diagnostics: Diagnostics,
767
+ rawEnv: RawEnvironment
768
+ ): RawEnvironment {
769
+ if (rawEnv["route"] === "") {
770
+ diagnostics.warnings.push(
771
+ `The "route" field in your configuration is an empty string and will be ignored.\n` +
772
+ `Please remove the "route" field from your configuration.`
773
+ );
774
+ rawEnv["route"] = undefined;
775
+ }
776
+
777
+ return rawEnv;
671
778
  }
672
779
 
673
780
  /**
674
781
  * Validate that the field is a route.
675
782
  */
676
783
  const isRoute: ValidatorFn = (diagnostics, field, value) => {
677
- if (value !== undefined && !isValidRouteValue(value)) {
678
- diagnostics.errors.push(
679
- `Expected "${field}" to be either a string, or an object with shape { pattern, custom_domain, zone_id | zone_name }, but got ${JSON.stringify(
680
- value
681
- )}.`
682
- );
683
- return false;
684
- }
685
- return true;
784
+ if (value !== undefined && !isValidRouteValue(value)) {
785
+ diagnostics.errors.push(
786
+ `Expected "${field}" to be either a string, or an object with shape { pattern, custom_domain, zone_id | zone_name }, but got ${JSON.stringify(
787
+ value
788
+ )}.`
789
+ );
790
+ return false;
791
+ }
792
+ return true;
686
793
  };
687
794
 
688
795
  /**
689
796
  * Validate that the field is an array of routes.
690
797
  */
691
798
  const isRouteArray: ValidatorFn = (diagnostics, field, value) => {
692
- if (value === undefined) {
693
- return true;
694
- }
695
- if (!Array.isArray(value)) {
696
- diagnostics.errors.push(
697
- `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
698
- );
699
- return false;
700
- }
701
- const invalidRoutes = [];
702
- for (const item of value) {
703
- if (!isValidRouteValue(item)) {
704
- invalidRoutes.push(item);
705
- }
706
- }
707
- if (invalidRoutes.length > 0) {
708
- diagnostics.errors.push(
709
- `Expected "${field}" to be an array of either strings or objects with the shape { pattern, custom_domain, zone_id | zone_name }, but these weren't valid: ${JSON.stringify(
710
- invalidRoutes,
711
- null,
712
- 2
713
- )}.`
714
- );
715
- }
716
- return invalidRoutes.length === 0;
799
+ if (value === undefined) {
800
+ return true;
801
+ }
802
+ if (!Array.isArray(value)) {
803
+ diagnostics.errors.push(
804
+ `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
805
+ );
806
+ return false;
807
+ }
808
+ const invalidRoutes = [];
809
+ for (const item of value) {
810
+ if (!isValidRouteValue(item)) {
811
+ invalidRoutes.push(item);
812
+ }
813
+ }
814
+ if (invalidRoutes.length > 0) {
815
+ diagnostics.errors.push(
816
+ `Expected "${field}" to be an array of either strings or objects with the shape { pattern, custom_domain, zone_id | zone_name }, but these weren't valid: ${JSON.stringify(
817
+ invalidRoutes,
818
+ null,
819
+ 2
820
+ )}.`
821
+ );
822
+ }
823
+ return invalidRoutes.length === 0;
717
824
  };
718
825
 
719
- function validateRoute(
720
- diagnostics: Diagnostics,
721
- topLevelEnv: Environment | undefined,
722
- rawEnv: RawEnvironment
826
+ function normalizeAndValidateRoute(
827
+ diagnostics: Diagnostics,
828
+ topLevelEnv: Environment | undefined,
829
+ rawEnv: RawEnvironment
723
830
  ): Config["route"] {
724
- return inheritable(
725
- diagnostics,
726
- topLevelEnv,
727
- rawEnv,
728
- "route",
729
- isRoute,
730
- undefined
731
- );
831
+ return inheritable(
832
+ diagnostics,
833
+ topLevelEnv,
834
+ mutateEmptyStringRouteValue(diagnostics, rawEnv),
835
+ "route",
836
+ isRoute,
837
+ undefined
838
+ );
732
839
  }
733
840
 
734
841
  function validateRoutes(
735
- diagnostics: Diagnostics,
736
- topLevelEnv: Environment | undefined,
737
- rawEnv: RawEnvironment
842
+ diagnostics: Diagnostics,
843
+ topLevelEnv: Environment | undefined,
844
+ rawEnv: RawEnvironment
738
845
  ): Config["routes"] {
739
- return inheritable(
740
- diagnostics,
741
- topLevelEnv,
742
- rawEnv,
743
- "routes",
744
- all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
745
- undefined
746
- );
846
+ return inheritable(
847
+ diagnostics,
848
+ topLevelEnv,
849
+ rawEnv,
850
+ "routes",
851
+ all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
852
+ undefined
853
+ );
747
854
  }
748
855
 
749
856
  /**
750
857
  * Validate top-level environment configuration and return the normalized values.
751
858
  */
752
859
  function normalizeAndValidateEnvironment(
753
- diagnostics: Diagnostics,
754
- configPath: string | undefined,
755
- topLevelEnv: RawEnvironment
860
+ diagnostics: Diagnostics,
861
+ configPath: string | undefined,
862
+ topLevelEnv: RawEnvironment
756
863
  ): Environment;
757
864
  /**
758
865
  * Validate the named environment configuration and return the normalized values.
759
866
  */
760
867
  function normalizeAndValidateEnvironment(
761
- diagnostics: Diagnostics,
762
- configPath: string | undefined,
763
- rawEnv: RawEnvironment,
764
- envName: string,
765
- topLevelEnv: Environment,
766
- isLegacyEnv: boolean,
767
- rawConfig: RawConfig
868
+ diagnostics: Diagnostics,
869
+ configPath: string | undefined,
870
+ rawEnv: RawEnvironment,
871
+ envName: string,
872
+ topLevelEnv: Environment,
873
+ isLegacyEnv: boolean,
874
+ rawConfig: RawConfig
768
875
  ): Environment;
769
876
  function normalizeAndValidateEnvironment(
770
- diagnostics: Diagnostics,
771
- configPath: string | undefined,
772
- rawEnv: RawEnvironment,
773
- envName = "top level",
774
- topLevelEnv?: Environment | undefined,
775
- isLegacyEnv?: boolean,
776
- rawConfig?: RawConfig | undefined
877
+ diagnostics: Diagnostics,
878
+ configPath: string | undefined,
879
+ rawEnv: RawEnvironment,
880
+ envName = "top level",
881
+ topLevelEnv?: Environment | undefined,
882
+ isLegacyEnv?: boolean,
883
+ rawConfig?: RawConfig | undefined
777
884
  ): Environment {
778
- deprecated(
779
- diagnostics,
780
- rawEnv,
781
- "zone_id",
782
- "This is unnecessary since we can deduce this from routes directly.",
783
- false // We need to leave this in-place for the moment since `route` commands might use it.
784
- );
785
-
786
- // The field "experimental_services" doesn't exist anymore in the config, but we still want to error about any older usage.
787
- // TODO: remove this before GA.
788
- deprecated(
789
- diagnostics,
790
- rawEnv,
791
- "experimental_services",
792
- `The "experimental_services" field is no longer supported. Simply rename the [experimental_services] field to [services].`,
793
- true
794
- );
795
-
796
- experimental(diagnostics, rawEnv, "unsafe");
797
- experimental(diagnostics, rawEnv, "services");
798
-
799
- const route = validateRoute(diagnostics, topLevelEnv, rawEnv);
800
-
801
- const routes = validateRoutes(diagnostics, topLevelEnv, rawEnv);
802
-
803
- const workers_dev = inheritable(
804
- diagnostics,
805
- topLevelEnv,
806
- rawEnv,
807
- "workers_dev",
808
- isBoolean,
809
- undefined
810
- );
811
-
812
- const { deprecatedUpload, ...build } = normalizeAndValidateBuild(
813
- diagnostics,
814
- rawEnv,
815
- rawEnv.build ?? topLevelEnv?.build ?? {},
816
- configPath
817
- );
818
-
819
- const environment: Environment = {
820
- // Inherited fields
821
- account_id: inheritableInLegacyEnvironments(
822
- diagnostics,
823
- isLegacyEnv,
824
- topLevelEnv,
825
- rawEnv,
826
- "account_id",
827
- isString,
828
- undefined,
829
- undefined
830
- ),
831
- compatibility_date: inheritable(
832
- diagnostics,
833
- topLevelEnv,
834
- rawEnv,
835
- "compatibility_date",
836
- isString,
837
- undefined
838
- ),
839
- compatibility_flags: inheritable(
840
- diagnostics,
841
- topLevelEnv,
842
- rawEnv,
843
- "compatibility_flags",
844
- isStringArray,
845
- []
846
- ),
847
- jsx_factory: inheritable(
848
- diagnostics,
849
- topLevelEnv,
850
- rawEnv,
851
- "jsx_factory",
852
- isString,
853
- "React.createElement"
854
- ),
855
- jsx_fragment: inheritable(
856
- diagnostics,
857
- topLevelEnv,
858
- rawEnv,
859
- "jsx_fragment",
860
- isString,
861
- "React.Fragment"
862
- ),
863
- tsconfig: validateAndNormalizeTsconfig(
864
- diagnostics,
865
- topLevelEnv,
866
- rawEnv,
867
- configPath
868
- ),
869
- rules: validateAndNormalizeRules(
870
- diagnostics,
871
- topLevelEnv,
872
- rawEnv,
873
- deprecatedUpload?.rules,
874
- envName
875
- ),
876
- name: inheritableInLegacyEnvironments(
877
- diagnostics,
878
- isLegacyEnv,
879
- topLevelEnv,
880
- rawEnv,
881
- "name",
882
- isValidName,
883
- appendEnvName(envName),
884
- undefined
885
- ),
886
- main: normalizeAndValidateMainField(
887
- configPath,
888
- inheritable(
889
- diagnostics,
890
- topLevelEnv,
891
- rawEnv,
892
- "main",
893
- isString,
894
- undefined
895
- ),
896
- deprecatedUpload
897
- ),
898
- route,
899
- routes,
900
- triggers: inheritable(
901
- diagnostics,
902
- topLevelEnv,
903
- rawEnv,
904
- "triggers",
905
- isObjectWith("crons"),
906
- { crons: [] }
907
- ),
908
- usage_model: inheritable(
909
- diagnostics,
910
- topLevelEnv,
911
- rawEnv,
912
- "usage_model",
913
- isOneOf("bundled", "unbound"),
914
- undefined
915
- ),
916
- build,
917
- workers_dev,
918
- // Not inherited fields
919
- vars: notInheritable(
920
- diagnostics,
921
- topLevelEnv,
922
- rawConfig,
923
- rawEnv,
924
- envName,
925
- "vars",
926
- validateVars(envName),
927
- {}
928
- ),
929
- durable_objects: notInheritable(
930
- diagnostics,
931
- topLevelEnv,
932
- rawConfig,
933
- rawEnv,
934
- envName,
935
- "durable_objects",
936
- validateBindingsProperty(envName, validateDurableObjectBinding),
937
- {
938
- bindings: [],
939
- }
940
- ),
941
- kv_namespaces: notInheritable(
942
- diagnostics,
943
- topLevelEnv,
944
- rawConfig,
945
- rawEnv,
946
- envName,
947
- "kv_namespaces",
948
- validateBindingArray(envName, validateKVBinding),
949
- []
950
- ),
951
- r2_buckets: notInheritable(
952
- diagnostics,
953
- topLevelEnv,
954
- rawConfig,
955
- rawEnv,
956
- envName,
957
- "r2_buckets",
958
- validateBindingArray(envName, validateR2Binding),
959
- []
960
- ),
961
- services: notInheritable(
962
- diagnostics,
963
- topLevelEnv,
964
- rawConfig,
965
- rawEnv,
966
- envName,
967
- "services",
968
- validateBindingArray(envName, validateServiceBinding),
969
- []
970
- ),
971
- unsafe: notInheritable(
972
- diagnostics,
973
- topLevelEnv,
974
- rawConfig,
975
- rawEnv,
976
- envName,
977
- "unsafe",
978
- validateBindingsProperty(envName, validateUnsafeBinding),
979
- {
980
- bindings: [],
981
- }
982
- ),
983
- zone_id: rawEnv.zone_id,
984
- minify: inheritable(
985
- diagnostics,
986
- topLevelEnv,
987
- rawEnv,
988
- "minify",
989
- isBoolean,
990
- undefined
991
- ),
992
- node_compat: inheritable(
993
- diagnostics,
994
- topLevelEnv,
995
- rawEnv,
996
- "node_compat",
997
- isBoolean,
998
- undefined
999
- ),
1000
- };
1001
-
1002
- return environment;
885
+ deprecated(
886
+ diagnostics,
887
+ rawEnv,
888
+ "kv-namespaces",
889
+ `The "kv-namespaces" field is no longer supported, please rename to "kv_namespaces"`,
890
+ true
891
+ );
892
+ deprecated(
893
+ diagnostics,
894
+ rawEnv,
895
+ "zone_id",
896
+ "This is unnecessary since we can deduce this from routes directly.",
897
+ false // We need to leave this in-place for the moment since `route` commands might use it.
898
+ );
899
+
900
+ // The field "experimental_services" doesn't exist anymore in the config, but we still want to error about any older usage.
901
+
902
+ deprecated(
903
+ diagnostics,
904
+ rawEnv,
905
+ "experimental_services",
906
+ `The "experimental_services" field is no longer supported. Simply rename the [experimental_services] field to [services].`,
907
+ true
908
+ );
909
+
910
+ experimental(diagnostics, rawEnv, "unsafe");
911
+ experimental(diagnostics, rawEnv, "services");
912
+
913
+ const route = normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv);
914
+
915
+ const account_id = inheritableInLegacyEnvironments(
916
+ diagnostics,
917
+ isLegacyEnv,
918
+ topLevelEnv,
919
+ mutateEmptyStringAccountIDValue(diagnostics, rawEnv),
920
+ "account_id",
921
+ isString,
922
+ undefined,
923
+ undefined
924
+ );
925
+
926
+ const routes = validateRoutes(diagnostics, topLevelEnv, rawEnv);
927
+
928
+ const workers_dev = inheritable(
929
+ diagnostics,
930
+ topLevelEnv,
931
+ rawEnv,
932
+ "workers_dev",
933
+ isBoolean,
934
+ undefined
935
+ );
936
+
937
+ const { deprecatedUpload, ...build } = normalizeAndValidateBuild(
938
+ diagnostics,
939
+ rawEnv,
940
+ rawEnv.build ?? topLevelEnv?.build ?? {},
941
+ configPath
942
+ );
943
+
944
+ const environment: Environment = {
945
+ // Inherited fields
946
+ account_id,
947
+ compatibility_date: inheritable(
948
+ diagnostics,
949
+ topLevelEnv,
950
+ rawEnv,
951
+ "compatibility_date",
952
+ isString,
953
+ undefined
954
+ ),
955
+ compatibility_flags: inheritable(
956
+ diagnostics,
957
+ topLevelEnv,
958
+ rawEnv,
959
+ "compatibility_flags",
960
+ isStringArray,
961
+ []
962
+ ),
963
+ jsx_factory: inheritable(
964
+ diagnostics,
965
+ topLevelEnv,
966
+ rawEnv,
967
+ "jsx_factory",
968
+ isString,
969
+ "React.createElement"
970
+ ),
971
+ jsx_fragment: inheritable(
972
+ diagnostics,
973
+ topLevelEnv,
974
+ rawEnv,
975
+ "jsx_fragment",
976
+ isString,
977
+ "React.Fragment"
978
+ ),
979
+ tsconfig: validateAndNormalizeTsconfig(
980
+ diagnostics,
981
+ topLevelEnv,
982
+ rawEnv,
983
+ configPath
984
+ ),
985
+ rules: validateAndNormalizeRules(
986
+ diagnostics,
987
+ topLevelEnv,
988
+ rawEnv,
989
+ deprecatedUpload?.rules,
990
+ envName
991
+ ),
992
+ name: inheritableInLegacyEnvironments(
993
+ diagnostics,
994
+ isLegacyEnv,
995
+ topLevelEnv,
996
+ rawEnv,
997
+ "name",
998
+ isValidName,
999
+ appendEnvName(envName),
1000
+ undefined
1001
+ ),
1002
+ main: normalizeAndValidateMainField(
1003
+ configPath,
1004
+ inheritable(
1005
+ diagnostics,
1006
+ topLevelEnv,
1007
+ rawEnv,
1008
+ "main",
1009
+ isString,
1010
+ undefined
1011
+ ),
1012
+ deprecatedUpload
1013
+ ),
1014
+ route,
1015
+ routes,
1016
+ triggers: inheritable(
1017
+ diagnostics,
1018
+ topLevelEnv,
1019
+ rawEnv,
1020
+ "triggers",
1021
+ isObjectWith("crons"),
1022
+ { crons: [] }
1023
+ ),
1024
+ usage_model: inheritable(
1025
+ diagnostics,
1026
+ topLevelEnv,
1027
+ rawEnv,
1028
+ "usage_model",
1029
+ isOneOf("bundled", "unbound"),
1030
+ undefined
1031
+ ),
1032
+ build,
1033
+ workers_dev,
1034
+ // Not inherited fields
1035
+ vars: notInheritable(
1036
+ diagnostics,
1037
+ topLevelEnv,
1038
+ rawConfig,
1039
+ rawEnv,
1040
+ envName,
1041
+ "vars",
1042
+ validateVars(envName),
1043
+ {}
1044
+ ),
1045
+ define: notInheritable(
1046
+ diagnostics,
1047
+ topLevelEnv,
1048
+ rawConfig,
1049
+ rawEnv,
1050
+ envName,
1051
+ "define",
1052
+ validateDefines(envName),
1053
+ {}
1054
+ ),
1055
+ durable_objects: notInheritable(
1056
+ diagnostics,
1057
+ topLevelEnv,
1058
+ rawConfig,
1059
+ rawEnv,
1060
+ envName,
1061
+ "durable_objects",
1062
+ validateBindingsProperty(envName, validateDurableObjectBinding),
1063
+ {
1064
+ bindings: [],
1065
+ }
1066
+ ),
1067
+ kv_namespaces: notInheritable(
1068
+ diagnostics,
1069
+ topLevelEnv,
1070
+ rawConfig,
1071
+ rawEnv,
1072
+ envName,
1073
+ "kv_namespaces",
1074
+ validateBindingArray(envName, validateKVBinding),
1075
+ []
1076
+ ),
1077
+ queues: notInheritable(
1078
+ diagnostics,
1079
+ topLevelEnv,
1080
+ rawConfig,
1081
+ rawEnv,
1082
+ envName,
1083
+ "queues",
1084
+ validateQueues(envName),
1085
+ { producers: [], consumers: [] }
1086
+ ),
1087
+ r2_buckets: notInheritable(
1088
+ diagnostics,
1089
+ topLevelEnv,
1090
+ rawConfig,
1091
+ rawEnv,
1092
+ envName,
1093
+ "r2_buckets",
1094
+ validateBindingArray(envName, validateR2Binding),
1095
+ []
1096
+ ),
1097
+ d1_databases: notInheritable(
1098
+ diagnostics,
1099
+ topLevelEnv,
1100
+ rawConfig,
1101
+ rawEnv,
1102
+ envName,
1103
+ "d1_databases",
1104
+ validateBindingArray(envName, validateD1Binding),
1105
+ []
1106
+ ),
1107
+ services: notInheritable(
1108
+ diagnostics,
1109
+ topLevelEnv,
1110
+ rawConfig,
1111
+ rawEnv,
1112
+ envName,
1113
+ "services",
1114
+ validateBindingArray(envName, validateServiceBinding),
1115
+ []
1116
+ ),
1117
+ analytics_engine_datasets: notInheritable(
1118
+ diagnostics,
1119
+ topLevelEnv,
1120
+ rawConfig,
1121
+ rawEnv,
1122
+ envName,
1123
+ "analytics_engine_datasets",
1124
+ validateBindingArray(envName, validateAnalyticsEngineBinding),
1125
+ []
1126
+ ),
1127
+ dispatch_namespaces: notInheritable(
1128
+ diagnostics,
1129
+ topLevelEnv,
1130
+ rawConfig,
1131
+ rawEnv,
1132
+ envName,
1133
+ "dispatch_namespaces",
1134
+ validateBindingArray(envName, validateWorkerNamespaceBinding),
1135
+ []
1136
+ ),
1137
+ mtls_certificates: notInheritable(
1138
+ diagnostics,
1139
+ topLevelEnv,
1140
+ rawConfig,
1141
+ rawEnv,
1142
+ envName,
1143
+ "mtls_certificates",
1144
+ validateBindingArray(envName, validateMTlsCertificateBinding),
1145
+ []
1146
+ ),
1147
+ logfwdr: inheritable(
1148
+ diagnostics,
1149
+ topLevelEnv,
1150
+ rawEnv,
1151
+ "logfwdr",
1152
+ validateBindingsProperty(envName, validateCflogfwdrBinding),
1153
+ {
1154
+ schema: undefined,
1155
+ bindings: [],
1156
+ }
1157
+ ),
1158
+ unsafe: notInheritable(
1159
+ diagnostics,
1160
+ topLevelEnv,
1161
+ rawConfig,
1162
+ rawEnv,
1163
+ envName,
1164
+ "unsafe",
1165
+ validateBindingsProperty(envName, validateUnsafeBinding),
1166
+ {
1167
+ bindings: [],
1168
+ }
1169
+ ),
1170
+ zone_id: rawEnv.zone_id,
1171
+ no_bundle: inheritable(
1172
+ diagnostics,
1173
+ topLevelEnv,
1174
+ rawEnv,
1175
+ "no_bundle",
1176
+ isBoolean,
1177
+ undefined
1178
+ ),
1179
+ minify: inheritable(
1180
+ diagnostics,
1181
+ topLevelEnv,
1182
+ rawEnv,
1183
+ "minify",
1184
+ isBoolean,
1185
+ undefined
1186
+ ),
1187
+ node_compat: inheritable(
1188
+ diagnostics,
1189
+ topLevelEnv,
1190
+ rawEnv,
1191
+ "node_compat",
1192
+ isBoolean,
1193
+ undefined
1194
+ ),
1195
+ first_party_worker: inheritable(
1196
+ diagnostics,
1197
+ topLevelEnv,
1198
+ rawEnv,
1199
+ "first_party_worker",
1200
+ isBoolean,
1201
+ undefined
1202
+ ),
1203
+ logpush: inheritable(
1204
+ diagnostics,
1205
+ topLevelEnv,
1206
+ rawEnv,
1207
+ "logpush",
1208
+ isBoolean,
1209
+ undefined
1210
+ ),
1211
+ };
1212
+
1213
+ return environment;
1003
1214
  }
1004
1215
 
1005
1216
  function validateAndNormalizeTsconfig(
1006
- diagnostics: Diagnostics,
1007
- topLevelEnv: Environment | undefined,
1008
- rawEnv: RawEnvironment,
1009
- configPath: string | undefined
1217
+ diagnostics: Diagnostics,
1218
+ topLevelEnv: Environment | undefined,
1219
+ rawEnv: RawEnvironment,
1220
+ configPath: string | undefined
1010
1221
  ) {
1011
- const tsconfig = inheritable(
1012
- diagnostics,
1013
- topLevelEnv,
1014
- rawEnv,
1015
- "tsconfig",
1016
- isString,
1017
- undefined
1018
- );
1019
-
1020
- return configPath && tsconfig
1021
- ? path.relative(
1022
- process.cwd(),
1023
- path.join(path.dirname(configPath), tsconfig)
1024
- )
1025
- : tsconfig;
1222
+ const tsconfig = inheritable(
1223
+ diagnostics,
1224
+ topLevelEnv,
1225
+ rawEnv,
1226
+ "tsconfig",
1227
+ isString,
1228
+ undefined
1229
+ );
1230
+
1231
+ return configPath && tsconfig
1232
+ ? path.relative(
1233
+ process.cwd(),
1234
+ path.join(path.dirname(configPath), tsconfig)
1235
+ )
1236
+ : tsconfig;
1026
1237
  }
1027
1238
 
1028
1239
  const validateAndNormalizeRules = (
1029
- diagnostics: Diagnostics,
1030
- topLevelEnv: Environment | undefined,
1031
- rawEnv: RawEnvironment,
1032
- deprecatedRules: Rule[] | undefined,
1033
- envName: string
1240
+ diagnostics: Diagnostics,
1241
+ topLevelEnv: Environment | undefined,
1242
+ rawEnv: RawEnvironment,
1243
+ deprecatedRules: Rule[] | undefined,
1244
+ envName: string
1034
1245
  ): Rule[] => {
1035
- if (topLevelEnv === undefined) {
1036
- // Only create errors/warnings for the top-level environment
1037
- if (rawEnv.rules && deprecatedRules) {
1038
- diagnostics.errors.push(
1039
- `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
1040
- );
1041
- } else if (deprecatedRules) {
1042
- diagnostics.warnings.push(
1043
- `Deprecation: The \`build.upload.rules\` config field is no longer used, the rules should be specified via the \`rules\` config field. Delete the \`build.upload\` field from the configuration file, and add this:\n` +
1044
- "```\n" +
1045
- TOML.stringify({ rules: deprecatedRules }) +
1046
- "```"
1047
- );
1048
- }
1049
- }
1050
-
1051
- return inheritable(
1052
- diagnostics,
1053
- topLevelEnv,
1054
- rawEnv,
1055
- "rules",
1056
- validateRules(envName),
1057
- deprecatedRules ?? []
1058
- );
1246
+ if (topLevelEnv === undefined) {
1247
+ // Only create errors/warnings for the top-level environment
1248
+ if (rawEnv.rules && deprecatedRules) {
1249
+ diagnostics.errors.push(
1250
+ `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
1251
+ );
1252
+ } else if (deprecatedRules) {
1253
+ diagnostics.warnings.push(
1254
+ `Deprecation: The \`build.upload.rules\` config field is no longer used, the rules should be specified via the \`rules\` config field. Delete the \`build.upload\` field from the configuration file, and add this:\n` +
1255
+ "```\n" +
1256
+ TOML.stringify({ rules: deprecatedRules }) +
1257
+ "```"
1258
+ );
1259
+ }
1260
+ }
1261
+
1262
+ return inheritable(
1263
+ diagnostics,
1264
+ topLevelEnv,
1265
+ rawEnv,
1266
+ "rules",
1267
+ validateRules(envName),
1268
+ deprecatedRules ?? []
1269
+ );
1059
1270
  };
1060
1271
 
1061
1272
  const validateRules =
1062
- (envName: string): ValidatorFn =>
1063
- (diagnostics, field, envValue, config) => {
1064
- if (!envValue) {
1065
- return true;
1066
- }
1067
- const fieldPath =
1068
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1069
- if (!Array.isArray(envValue)) {
1070
- diagnostics.errors.push(
1071
- `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1072
- envValue
1073
- )}.`
1074
- );
1075
- return false;
1076
- }
1077
-
1078
- let isValid = true;
1079
- for (let i = 0; i < envValue.length; i++) {
1080
- isValid =
1081
- validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) &&
1082
- isValid;
1083
- }
1084
- return isValid;
1085
- };
1273
+ (envName: string): ValidatorFn =>
1274
+ (diagnostics, field, envValue, config) => {
1275
+ if (!envValue) {
1276
+ return true;
1277
+ }
1278
+ const fieldPath =
1279
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1280
+ if (!Array.isArray(envValue)) {
1281
+ diagnostics.errors.push(
1282
+ `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1283
+ envValue
1284
+ )}.`
1285
+ );
1286
+ return false;
1287
+ }
1288
+
1289
+ let isValid = true;
1290
+ for (let i = 0; i < envValue.length; i++) {
1291
+ isValid =
1292
+ validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) &&
1293
+ isValid;
1294
+ }
1295
+ return isValid;
1296
+ };
1086
1297
 
1087
1298
  const validateRule: ValidatorFn = (diagnostics, field, value) => {
1088
- if (typeof value !== "object" || value === null) {
1089
- diagnostics.errors.push(
1090
- `"${field}" should be an object but got ${JSON.stringify(value)}.`
1091
- );
1092
- return false;
1093
- }
1094
- // Rules must have a type string and glob string array, and optionally a fallthrough boolean.
1095
- let isValid = true;
1096
- const rule = value as Rule;
1097
-
1098
- if (
1099
- !isRequiredProperty(rule, "type", "string", [
1100
- "ESModule",
1101
- "CommonJS",
1102
- "CompiledWasm",
1103
- "Text",
1104
- "Data",
1105
- ])
1106
- ) {
1107
- diagnostics.errors.push(
1108
- `bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
1109
- );
1110
- isValid = false;
1111
- }
1112
-
1113
- isValid =
1114
- validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") &&
1115
- isValid;
1116
-
1117
- if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
1118
- diagnostics.errors.push(
1119
- `the field "fallthrough", when present, should be a boolean.`
1120
- );
1121
- isValid = false;
1122
- }
1123
-
1124
- return isValid;
1299
+ if (typeof value !== "object" || value === null) {
1300
+ diagnostics.errors.push(
1301
+ `"${field}" should be an object but got ${JSON.stringify(value)}.`
1302
+ );
1303
+ return false;
1304
+ }
1305
+ // Rules must have a type string and glob string array, and optionally a fallthrough boolean.
1306
+ let isValid = true;
1307
+ const rule = value as Rule;
1308
+
1309
+ if (
1310
+ !isRequiredProperty(rule, "type", "string", [
1311
+ "ESModule",
1312
+ "CommonJS",
1313
+ "CompiledWasm",
1314
+ "Text",
1315
+ "Data",
1316
+ ])
1317
+ ) {
1318
+ diagnostics.errors.push(
1319
+ `bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
1320
+ );
1321
+ isValid = false;
1322
+ }
1323
+
1324
+ isValid =
1325
+ validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") &&
1326
+ isValid;
1327
+
1328
+ if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
1329
+ diagnostics.errors.push(
1330
+ `the field "fallthrough", when present, should be a boolean.`
1331
+ );
1332
+ isValid = false;
1333
+ }
1334
+
1335
+ return isValid;
1125
1336
  };
1126
1337
 
1338
+ const validateDefines =
1339
+ (envName: string): ValidatorFn =>
1340
+ (diagnostics, field, value, config) => {
1341
+ let isValid = true;
1342
+ const fieldPath =
1343
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1344
+
1345
+ if (typeof value === "object" && value !== null) {
1346
+ for (const varName in value) {
1347
+ // some casting here to appease typescript
1348
+ // even though the value might not match the type
1349
+ if (typeof (value as Record<string, string>)[varName] !== "string") {
1350
+ diagnostics.errors.push(
1351
+ `The field "${fieldPath}.${varName}" should be a string but got ${JSON.stringify(
1352
+ (value as Record<string, string>)[varName]
1353
+ )}.`
1354
+ );
1355
+ isValid = false;
1356
+ }
1357
+ }
1358
+ } else {
1359
+ if (value !== undefined) {
1360
+ diagnostics.errors.push(
1361
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1362
+ value
1363
+ )}.\n`
1364
+ );
1365
+ isValid = false;
1366
+ }
1367
+ }
1368
+
1369
+ const configDefines = Object.keys(config?.define ?? {});
1370
+
1371
+ // If there are no top level vars then there is nothing to do here.
1372
+ if (configDefines.length > 0) {
1373
+ if (typeof value === "object" && value !== null) {
1374
+ const configEnvDefines = config === undefined ? [] : Object.keys(value);
1375
+
1376
+ for (const varName of configDefines) {
1377
+ if (!(varName in value)) {
1378
+ diagnostics.warnings.push(
1379
+ `"define.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
1380
+ `This is not what you probably want, since "define" configuration is not inherited by environments.\n` +
1381
+ `Please add "define.${varName}" to "env.${envName}".`
1382
+ );
1383
+ }
1384
+ }
1385
+ for (const varName of configEnvDefines) {
1386
+ if (!configDefines.includes(varName)) {
1387
+ diagnostics.warnings.push(
1388
+ `"${varName}" exists on "env.${envName}", but not on the top level.\n` +
1389
+ `This is not what you probably want, since "define" configuration within environments can only override existing top level "define" configuration\n` +
1390
+ `Please remove "${fieldPath}.${varName}", or add "define.${varName}".`
1391
+ );
1392
+ }
1393
+ }
1394
+ }
1395
+ }
1396
+
1397
+ return isValid;
1398
+ };
1399
+
1127
1400
  const validateVars =
1128
- (envName: string): ValidatorFn =>
1129
- (diagnostics, field, value, config) => {
1130
- let isValid = true;
1131
- const fieldPath =
1132
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1133
- const configVars = Object.keys(config?.vars ?? {});
1134
- // If there are no top level vars then there is nothing to do here.
1135
- if (configVars.length > 0) {
1136
- if (typeof value !== "object" || value === null) {
1137
- diagnostics.errors.push(
1138
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1139
- value
1140
- )}.\n`
1141
- );
1142
- isValid = false;
1143
- } else {
1144
- for (const varName of configVars) {
1145
- if (!(varName in value)) {
1146
- diagnostics.warnings.push(
1147
- `"vars.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
1148
- `This is not what you probably want, since "vars" configuration is not inherited by environments.\n` +
1149
- `Please add "vars.${varName}" to "env.${envName}".`
1150
- );
1151
- }
1152
- }
1153
- }
1154
- }
1155
- return isValid;
1156
- };
1401
+ (envName: string): ValidatorFn =>
1402
+ (diagnostics, field, value, config) => {
1403
+ let isValid = true;
1404
+ const fieldPath =
1405
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1406
+ const configVars = Object.keys(config?.vars ?? {});
1407
+ // If there are no top level vars then there is nothing to do here.
1408
+ if (configVars.length > 0) {
1409
+ if (typeof value !== "object" || value === null) {
1410
+ diagnostics.errors.push(
1411
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1412
+ value
1413
+ )}.\n`
1414
+ );
1415
+ isValid = false;
1416
+ } else {
1417
+ for (const varName of configVars) {
1418
+ if (!(varName in value)) {
1419
+ diagnostics.warnings.push(
1420
+ `"vars.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
1421
+ `This is not what you probably want, since "vars" configuration is not inherited by environments.\n` +
1422
+ `Please add "vars.${varName}" to "env.${envName}".`
1423
+ );
1424
+ }
1425
+ }
1426
+ }
1427
+ }
1428
+ return isValid;
1429
+ };
1157
1430
 
1158
1431
  const validateBindingsProperty =
1159
- (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1160
- (diagnostics, field, value, config) => {
1161
- let isValid = true;
1162
- const fieldPath =
1163
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1164
-
1165
- if (value !== undefined) {
1166
- // Check the validity of the `value` as a bindings container.
1167
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
1168
- diagnostics.errors.push(
1169
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1170
- value
1171
- )}.`
1172
- );
1173
- isValid = false;
1174
- } else if (!hasProperty(value, "bindings")) {
1175
- diagnostics.errors.push(
1176
- `The field "${fieldPath}" is missing the required "bindings" property.`
1177
- );
1178
- isValid = false;
1179
- } else if (!Array.isArray(value.bindings)) {
1180
- diagnostics.errors.push(
1181
- `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
1182
- value.bindings
1183
- )}.`
1184
- );
1185
- isValid = false;
1186
- } else {
1187
- for (let i = 0; i < value.bindings.length; i++) {
1188
- const binding = value.bindings[i];
1189
- const bindingDiagnostics = new Diagnostics(
1190
- `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
1191
- );
1192
- isValid =
1193
- validateBinding(
1194
- bindingDiagnostics,
1195
- `${fieldPath}.bindings[${i}]`,
1196
- binding,
1197
- config
1198
- ) && isValid;
1199
- diagnostics.addChild(bindingDiagnostics);
1200
- }
1201
- }
1202
-
1203
- const configBindingNames = getBindingNames(
1204
- config?.[field as keyof Environment]
1205
- );
1206
- if (isValid && configBindingNames.length > 0) {
1207
- // If there are top level bindings then check that they all appear in the environment.
1208
- const envBindingNames = new Set(getBindingNames(value));
1209
- const missingBindings = configBindingNames.filter(
1210
- (name) => !envBindingNames.has(name)
1211
- );
1212
- if (missingBindings.length > 0) {
1213
- diagnostics.warnings.push(
1214
- `The following bindings are at the top level, but not on "env.${envName}".\n` +
1215
- `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1216
- `Please add a binding for each to "${fieldPath}.bindings":\n` +
1217
- missingBindings.map((name) => `- ${name}`).join("\n")
1218
- );
1219
- }
1220
- }
1221
- }
1222
- return isValid;
1223
- };
1432
+ (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1433
+ (diagnostics, field, value, config) => {
1434
+ let isValid = true;
1435
+ const fieldPath =
1436
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1437
+
1438
+ if (value !== undefined) {
1439
+ // Check the validity of the `value` as a bindings container.
1440
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1441
+ diagnostics.errors.push(
1442
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1443
+ value
1444
+ )}.`
1445
+ );
1446
+ isValid = false;
1447
+ } else if (!hasProperty(value, "bindings")) {
1448
+ diagnostics.errors.push(
1449
+ `The field "${fieldPath}" is missing the required "bindings" property.`
1450
+ );
1451
+ isValid = false;
1452
+ } else if (!Array.isArray(value.bindings)) {
1453
+ diagnostics.errors.push(
1454
+ `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
1455
+ value.bindings
1456
+ )}.`
1457
+ );
1458
+ isValid = false;
1459
+ } else {
1460
+ for (let i = 0; i < value.bindings.length; i++) {
1461
+ const binding = value.bindings[i];
1462
+ const bindingDiagnostics = new Diagnostics(
1463
+ `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
1464
+ );
1465
+ isValid =
1466
+ validateBinding(
1467
+ bindingDiagnostics,
1468
+ `${fieldPath}.bindings[${i}]`,
1469
+ binding,
1470
+ config
1471
+ ) && isValid;
1472
+ diagnostics.addChild(bindingDiagnostics);
1473
+ }
1474
+ }
1475
+
1476
+ const configBindingNames = getBindingNames(
1477
+ config?.[field as keyof Environment]
1478
+ );
1479
+ if (isValid && configBindingNames.length > 0) {
1480
+ // If there are top level bindings then check that they all appear in the environment.
1481
+ const envBindingNames = new Set(getBindingNames(value));
1482
+ const missingBindings = configBindingNames.filter(
1483
+ (name) => !envBindingNames.has(name)
1484
+ );
1485
+ if (missingBindings.length > 0) {
1486
+ diagnostics.warnings.push(
1487
+ `The following bindings are at the top level, but not on "env.${envName}".\n` +
1488
+ `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1489
+ `Please add a binding for each to "${fieldPath}.bindings":\n` +
1490
+ missingBindings.map((name) => `- ${name}`).join("\n")
1491
+ );
1492
+ }
1493
+ }
1494
+ }
1495
+ return isValid;
1496
+ };
1224
1497
 
1225
1498
  /**
1226
1499
  * Check that the given field is a valid "durable_object" binding object.
1227
1500
  */
1228
1501
  const validateDurableObjectBinding: ValidatorFn = (
1229
- diagnostics,
1230
- field,
1231
- value
1502
+ diagnostics,
1503
+ field,
1504
+ value
1232
1505
  ) => {
1233
- if (typeof value !== "object" || value === null) {
1234
- diagnostics.errors.push(
1235
- `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
1236
- );
1237
- return false;
1238
- }
1239
-
1240
- // Durable Object bindings must have a name and class_name, and optionally a script_name and an environment.
1241
- let isValid = true;
1242
- if (!isRequiredProperty(value, "name", "string")) {
1243
- diagnostics.errors.push(`binding should have a string "name" field.`);
1244
- isValid = false;
1245
- }
1246
- if (!isRequiredProperty(value, "class_name", "string")) {
1247
- diagnostics.errors.push(`binding should have a string "class_name" field.`);
1248
- isValid = false;
1249
- }
1250
- if (!isOptionalProperty(value, "script_name", "string")) {
1251
- diagnostics.errors.push(
1252
- `the field "script_name", when present, should be a string.`
1253
- );
1254
- isValid = false;
1255
- }
1256
- // environment requires a script_name
1257
- if (!isOptionalProperty(value, "environment", "string")) {
1258
- diagnostics.errors.push(
1259
- `the field "environment", when present, should be a string.`
1260
- );
1261
- isValid = false;
1262
- }
1263
-
1264
- if ("environment" in value && !("script_name" in value)) {
1265
- diagnostics.errors.push(
1266
- `binding should have a "script_name" field if "environment" is present.`
1267
- );
1268
- isValid = false;
1269
- }
1270
-
1271
- return isValid;
1506
+ if (typeof value !== "object" || value === null) {
1507
+ diagnostics.errors.push(
1508
+ `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
1509
+ );
1510
+ return false;
1511
+ }
1512
+
1513
+ // Durable Object bindings must have a name and class_name, and optionally a script_name and an environment.
1514
+ let isValid = true;
1515
+ if (!isRequiredProperty(value, "name", "string")) {
1516
+ diagnostics.errors.push(`binding should have a string "name" field.`);
1517
+ isValid = false;
1518
+ }
1519
+ if (!isRequiredProperty(value, "class_name", "string")) {
1520
+ diagnostics.errors.push(`binding should have a string "class_name" field.`);
1521
+ isValid = false;
1522
+ }
1523
+ if (!isOptionalProperty(value, "script_name", "string")) {
1524
+ diagnostics.errors.push(
1525
+ `the field "script_name", when present, should be a string.`
1526
+ );
1527
+ isValid = false;
1528
+ }
1529
+ // environment requires a script_name
1530
+ if (!isOptionalProperty(value, "environment", "string")) {
1531
+ diagnostics.errors.push(
1532
+ `the field "environment", when present, should be a string.`
1533
+ );
1534
+ isValid = false;
1535
+ }
1536
+
1537
+ if ("environment" in value && !("script_name" in value)) {
1538
+ diagnostics.errors.push(
1539
+ `binding should have a "script_name" field if "environment" is present.`
1540
+ );
1541
+ isValid = false;
1542
+ }
1543
+
1544
+ return isValid;
1545
+ };
1546
+
1547
+ const validateCflogfwdrBinding: ValidatorFn = (diagnostics, field, value) => {
1548
+ if (typeof value !== "object" || value === null) {
1549
+ diagnostics.errors.push(
1550
+ `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
1551
+ );
1552
+ return false;
1553
+ }
1554
+
1555
+ let isValid = true;
1556
+ if (!isRequiredProperty(value, "name", "string")) {
1557
+ diagnostics.errors.push(`binding should have a string "name" field.`);
1558
+ isValid = false;
1559
+ }
1560
+
1561
+ if (!isRequiredProperty(value, "destination", "string")) {
1562
+ diagnostics.errors.push(
1563
+ `binding should have a string "destination" field.`
1564
+ );
1565
+ isValid = false;
1566
+ }
1567
+
1568
+ return isValid;
1272
1569
  };
1273
1570
 
1274
1571
  /**
@@ -1277,173 +1574,270 @@ const validateDurableObjectBinding: ValidatorFn = (
1277
1574
  * TODO: further validation of known unsafe bindings.
1278
1575
  */
1279
1576
  const validateUnsafeBinding: ValidatorFn = (diagnostics, field, value) => {
1280
- if (typeof value !== "object" || value === null) {
1281
- diagnostics.errors.push(
1282
- `Expected ${field} to be an object but got ${JSON.stringify(value)}.`
1283
- );
1284
- return false;
1285
- }
1286
-
1287
- let isValid = true;
1288
- // Unsafe bindings must have a name and type.
1289
- if (!isRequiredProperty(value, "name", "string")) {
1290
- diagnostics.errors.push(`binding should have a string "name" field.`);
1291
- isValid = false;
1292
- }
1293
- if (isRequiredProperty(value, "type", "string")) {
1294
- const safeBindings = [
1295
- "plain_text",
1296
- "json",
1297
- "wasm_module",
1298
- "data_blob",
1299
- "text_blob",
1300
- "kv_namespace",
1301
- "durable_object_namespace",
1302
- "r2_bucket",
1303
- "service",
1304
- ];
1305
-
1306
- if (safeBindings.includes(value.type)) {
1307
- diagnostics.warnings.push(
1308
- `The binding type "${value.type}" is directly supported by wrangler.\n` +
1309
- `Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.\n` +
1310
- "For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration"
1311
- );
1312
- }
1313
- } else {
1314
- diagnostics.errors.push(`binding should have a string "type" field.`);
1315
- isValid = false;
1316
- }
1317
- return isValid;
1577
+ if (typeof value !== "object" || value === null) {
1578
+ diagnostics.errors.push(
1579
+ `Expected ${field} to be an object but got ${JSON.stringify(value)}.`
1580
+ );
1581
+ return false;
1582
+ }
1583
+
1584
+ let isValid = true;
1585
+ // Unsafe bindings must have a name and type.
1586
+ if (!isRequiredProperty(value, "name", "string")) {
1587
+ diagnostics.errors.push(`binding should have a string "name" field.`);
1588
+ isValid = false;
1589
+ }
1590
+ if (isRequiredProperty(value, "type", "string")) {
1591
+ const safeBindings = [
1592
+ "plain_text",
1593
+ "json",
1594
+ "wasm_module",
1595
+ "data_blob",
1596
+ "text_blob",
1597
+ "kv_namespace",
1598
+ "durable_object_namespace",
1599
+ "d1_database",
1600
+ "r2_bucket",
1601
+ "service",
1602
+ "logfwdr",
1603
+ "mtls_certificate",
1604
+ ];
1605
+
1606
+ if (safeBindings.includes(value.type)) {
1607
+ diagnostics.warnings.push(
1608
+ `The binding type "${value.type}" is directly supported by wrangler.\n` +
1609
+ `Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.\n` +
1610
+ "For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration"
1611
+ );
1612
+ }
1613
+ } else {
1614
+ diagnostics.errors.push(`binding should have a string "type" field.`);
1615
+ isValid = false;
1616
+ }
1617
+ return isValid;
1318
1618
  };
1319
1619
 
1320
1620
  /**
1321
1621
  * Check that the given environment field is a valid array of bindings.
1322
1622
  */
1323
1623
  const validateBindingArray =
1324
- (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1325
- (diagnostics, field, envValue, config) => {
1326
- if (envValue === undefined) {
1327
- return true;
1328
- }
1329
-
1330
- const fieldPath =
1331
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1332
- if (!Array.isArray(envValue)) {
1333
- diagnostics.errors.push(
1334
- `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1335
- envValue
1336
- )}.`
1337
- );
1338
- return false;
1339
- }
1340
-
1341
- let isValid = true;
1342
- for (let i = 0; i < envValue.length; i++) {
1343
- isValid =
1344
- validateBinding(
1345
- diagnostics,
1346
- `${fieldPath}[${i}]`,
1347
- envValue[i],
1348
- config
1349
- ) && isValid;
1350
- }
1351
- const configValue = config?.[field as keyof Environment] as {
1352
- binding: unknown;
1353
- }[];
1354
- if (Array.isArray(configValue)) {
1355
- const configBindingNames = configValue.map((value) => value.binding);
1356
- // If there are no top level bindings then there is nothing to do here.
1357
- if (configBindingNames.length > 0) {
1358
- const envBindingNames = new Set(envValue.map((value) => value.binding));
1359
- for (const configBindingName of configBindingNames) {
1360
- if (!envBindingNames.has(configBindingName)) {
1361
- diagnostics.warnings.push(
1362
- `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".\n` +
1363
- `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1364
- `Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
1365
- );
1366
- }
1367
- }
1368
- }
1369
- }
1370
- return isValid;
1371
- };
1624
+ (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1625
+ (diagnostics, field, envValue, config) => {
1626
+ if (envValue === undefined) {
1627
+ return true;
1628
+ }
1629
+
1630
+ const fieldPath =
1631
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1632
+ if (!Array.isArray(envValue)) {
1633
+ diagnostics.errors.push(
1634
+ `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1635
+ envValue
1636
+ )}.`
1637
+ );
1638
+ return false;
1639
+ }
1640
+
1641
+ let isValid = true;
1642
+ for (let i = 0; i < envValue.length; i++) {
1643
+ isValid =
1644
+ validateBinding(
1645
+ diagnostics,
1646
+ `${fieldPath}[${i}]`,
1647
+ envValue[i],
1648
+ config
1649
+ ) && isValid;
1650
+ }
1651
+ const configValue = config?.[field as keyof Environment] as {
1652
+ binding: unknown;
1653
+ }[];
1654
+ if (Array.isArray(configValue)) {
1655
+ const configBindingNames = configValue.map((value) => value.binding);
1656
+ // If there are no top level bindings then there is nothing to do here.
1657
+ if (configBindingNames.length > 0) {
1658
+ const envBindingNames = new Set(envValue.map((value) => value.binding));
1659
+ for (const configBindingName of configBindingNames) {
1660
+ if (!envBindingNames.has(configBindingName)) {
1661
+ diagnostics.warnings.push(
1662
+ `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".\n` +
1663
+ `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1664
+ `Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
1665
+ );
1666
+ }
1667
+ }
1668
+ }
1669
+ }
1670
+ return isValid;
1671
+ };
1372
1672
 
1373
1673
  const validateKVBinding: ValidatorFn = (diagnostics, field, value) => {
1374
- if (typeof value !== "object" || value === null) {
1375
- diagnostics.errors.push(
1376
- `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
1377
- value
1378
- )}`
1379
- );
1380
- return false;
1381
- }
1382
- let isValid = true;
1383
- // KV bindings must have a binding and id.
1384
- if (!isRequiredProperty(value, "binding", "string")) {
1385
- diagnostics.errors.push(
1386
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1387
- value
1388
- )}.`
1389
- );
1390
- isValid = false;
1391
- }
1392
- if (!isRequiredProperty(value, "id", "string")) {
1393
- diagnostics.errors.push(
1394
- `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
1395
- value
1396
- )}.`
1397
- );
1398
- isValid = false;
1399
- }
1400
- if (!isOptionalProperty(value, "preview_id", "string")) {
1401
- diagnostics.errors.push(
1402
- `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
1403
- value
1404
- )}.`
1405
- );
1406
- isValid = false;
1407
- }
1408
- return isValid;
1674
+ if (typeof value !== "object" || value === null) {
1675
+ diagnostics.errors.push(
1676
+ `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
1677
+ value
1678
+ )}`
1679
+ );
1680
+ return false;
1681
+ }
1682
+ let isValid = true;
1683
+ // KV bindings must have a binding and id.
1684
+ if (!isRequiredProperty(value, "binding", "string")) {
1685
+ diagnostics.errors.push(
1686
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1687
+ value
1688
+ )}.`
1689
+ );
1690
+ isValid = false;
1691
+ }
1692
+ if (
1693
+ !isRequiredProperty(value, "id", "string") ||
1694
+ (value as { id: string }).id.length === 0
1695
+ ) {
1696
+ diagnostics.errors.push(
1697
+ `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
1698
+ value
1699
+ )}.`
1700
+ );
1701
+ isValid = false;
1702
+ }
1703
+ if (!isOptionalProperty(value, "preview_id", "string")) {
1704
+ diagnostics.errors.push(
1705
+ `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
1706
+ value
1707
+ )}.`
1708
+ );
1709
+ isValid = false;
1710
+ }
1711
+ return isValid;
1712
+ };
1713
+
1714
+ const validateQueueBinding: ValidatorFn = (diagnostics, field, value) => {
1715
+ if (typeof value !== "object" || value === null) {
1716
+ diagnostics.errors.push(
1717
+ `"queue" bindings should be objects, but got ${JSON.stringify(value)}`
1718
+ );
1719
+ return false;
1720
+ }
1721
+
1722
+ if (
1723
+ !validateAdditionalProperties(diagnostics, field, Object.keys(value), [
1724
+ "binding",
1725
+ "queue",
1726
+ ])
1727
+ ) {
1728
+ return false;
1729
+ }
1730
+
1731
+ // Queue bindings must have a binding and queue.
1732
+ let isValid = true;
1733
+ if (!isRequiredProperty(value, "binding", "string")) {
1734
+ diagnostics.errors.push(
1735
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1736
+ value
1737
+ )}.`
1738
+ );
1739
+ isValid = false;
1740
+ }
1741
+ if (
1742
+ !isRequiredProperty(value, "queue", "string") ||
1743
+ (value as { queue: string }).queue.length === 0
1744
+ ) {
1745
+ diagnostics.errors.push(
1746
+ `"${field}" bindings should have a string "queue" field but got ${JSON.stringify(
1747
+ value
1748
+ )}.`
1749
+ );
1750
+ isValid = false;
1751
+ }
1752
+ return isValid;
1409
1753
  };
1410
1754
 
1411
1755
  const validateR2Binding: ValidatorFn = (diagnostics, field, value) => {
1412
- if (typeof value !== "object" || value === null) {
1413
- diagnostics.errors.push(
1414
- `"r2_buckets" bindings should be objects, but got ${JSON.stringify(
1415
- value
1416
- )}`
1417
- );
1418
- return false;
1419
- }
1420
- let isValid = true;
1421
- // R2 bindings must have a binding and bucket_name.
1422
- if (!isRequiredProperty(value, "binding", "string")) {
1423
- diagnostics.errors.push(
1424
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1425
- value
1426
- )}.`
1427
- );
1428
- isValid = false;
1429
- }
1430
- if (!isRequiredProperty(value, "bucket_name", "string")) {
1431
- diagnostics.errors.push(
1432
- `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
1433
- value
1434
- )}.`
1435
- );
1436
- isValid = false;
1437
- }
1438
- if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
1439
- diagnostics.errors.push(
1440
- `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
1441
- value
1442
- )}.`
1443
- );
1444
- isValid = false;
1445
- }
1446
- return isValid;
1756
+ if (typeof value !== "object" || value === null) {
1757
+ diagnostics.errors.push(
1758
+ `"r2_buckets" bindings should be objects, but got ${JSON.stringify(
1759
+ value
1760
+ )}`
1761
+ );
1762
+ return false;
1763
+ }
1764
+ let isValid = true;
1765
+ // R2 bindings must have a binding and bucket_name.
1766
+ if (!isRequiredProperty(value, "binding", "string")) {
1767
+ diagnostics.errors.push(
1768
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1769
+ value
1770
+ )}.`
1771
+ );
1772
+ isValid = false;
1773
+ }
1774
+ if (
1775
+ !isRequiredProperty(value, "bucket_name", "string") ||
1776
+ (value as { bucket_name: string }).bucket_name.length === 0
1777
+ ) {
1778
+ diagnostics.errors.push(
1779
+ `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
1780
+ value
1781
+ )}.`
1782
+ );
1783
+ isValid = false;
1784
+ }
1785
+ if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
1786
+ diagnostics.errors.push(
1787
+ `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
1788
+ value
1789
+ )}.`
1790
+ );
1791
+ isValid = false;
1792
+ }
1793
+ return isValid;
1794
+ };
1795
+
1796
+ const validateD1Binding: ValidatorFn = (diagnostics, field, value) => {
1797
+ if (typeof value !== "object" || value === null) {
1798
+ diagnostics.errors.push(
1799
+ `"d1_databases" bindings should be objects, but got ${JSON.stringify(
1800
+ value
1801
+ )}`
1802
+ );
1803
+ return false;
1804
+ }
1805
+ let isValid = true;
1806
+ // D1 databases must have a binding and either a database_name or database_id.
1807
+ if (!isRequiredProperty(value, "binding", "string")) {
1808
+ diagnostics.errors.push(
1809
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1810
+ value
1811
+ )}.`
1812
+ );
1813
+ isValid = false;
1814
+ }
1815
+ if (
1816
+ // TODO: allow name only, where we look up the ID dynamically
1817
+ // !isOptionalProperty(value, "database_name", "string") &&
1818
+ !isRequiredProperty(value, "database_id", "string")
1819
+ ) {
1820
+ diagnostics.errors.push(
1821
+ `"${field}" bindings must have a "database_id" field but got ${JSON.stringify(
1822
+ value
1823
+ )}.`
1824
+ );
1825
+ isValid = false;
1826
+ }
1827
+ if (!isOptionalProperty(value, "preview_database_id", "string")) {
1828
+ diagnostics.errors.push(
1829
+ `"${field}" bindings should, optionally, have a string "preview_database_id" field but got ${JSON.stringify(
1830
+ value
1831
+ )}.`
1832
+ );
1833
+ isValid = false;
1834
+ }
1835
+ if (isValid && !process.env.NO_D1_WARNING) {
1836
+ diagnostics.warnings.push(
1837
+ "D1 Bindings are currently in alpha to allow the API to evolve before general availability.\nPlease report any issues to https://github.com/cloudflare/workers-sdk/issues/new/choose\nNote: Run this command with the environment variable NO_D1_WARNING=true to hide this message\n\nFor example: `export NO_D1_WARNING=true && wrangler <YOUR COMMAND HERE>`"
1838
+ );
1839
+ }
1840
+ return isValid;
1447
1841
  };
1448
1842
 
1449
1843
  /**
@@ -1455,126 +1849,350 @@ const validateR2Binding: ValidatorFn = (diagnostics, field, value) => {
1455
1849
  * the `DATA` global).
1456
1850
  */
1457
1851
  const validateBindingsHaveUniqueNames = (
1458
- diagnostics: Diagnostics,
1459
- {
1460
- durable_objects,
1461
- kv_namespaces,
1462
- r2_buckets,
1463
- text_blobs,
1464
- unsafe,
1465
- vars,
1466
- wasm_modules,
1467
- data_blobs,
1468
- }: Partial<Config>
1852
+ diagnostics: Diagnostics,
1853
+ {
1854
+ durable_objects,
1855
+ kv_namespaces,
1856
+ r2_buckets,
1857
+ analytics_engine_datasets,
1858
+ text_blobs,
1859
+ unsafe,
1860
+ vars,
1861
+ define,
1862
+ wasm_modules,
1863
+ data_blobs,
1864
+ }: Partial<Config>
1469
1865
  ): boolean => {
1470
- let hasDuplicates = false;
1471
-
1472
- const bindingsGroupedByType = {
1473
- "Durable Object": getBindingNames(durable_objects),
1474
- "KV Namespace": getBindingNames(kv_namespaces),
1475
- "R2 Bucket": getBindingNames(r2_buckets),
1476
- "Text Blob": getBindingNames(text_blobs),
1477
- Unsafe: getBindingNames(unsafe),
1478
- "Environment Variable": getBindingNames(vars),
1479
- "WASM Module": getBindingNames(wasm_modules),
1480
- "Data Blob": getBindingNames(data_blobs),
1481
- } as Record<string, string[]>;
1482
-
1483
- const bindingsGroupedByName: Record<string, string[]> = {};
1484
-
1485
- for (const bindingType in bindingsGroupedByType) {
1486
- const bindingNames = bindingsGroupedByType[bindingType];
1487
-
1488
- for (const bindingName of bindingNames) {
1489
- if (!(bindingName in bindingsGroupedByName)) {
1490
- bindingsGroupedByName[bindingName] = [];
1491
- }
1492
-
1493
- bindingsGroupedByName[bindingName].push(bindingType);
1494
- }
1495
- }
1496
-
1497
- for (const bindingName in bindingsGroupedByName) {
1498
- const bindingTypes = bindingsGroupedByName[bindingName];
1499
- if (bindingTypes.length < 2) {
1500
- // there's only one (or zero) binding(s) with this name, which is fine, actually
1501
- continue;
1502
- }
1503
-
1504
- hasDuplicates = true;
1505
-
1506
- // there's two types of duplicates we want to look for:
1507
- // - bindings with the same name of the same type (e.g. two Durable Objects both named "OBJ")
1508
- // - bindings with the same name of different types (a KV namespace and DO both named "DATA")
1509
-
1510
- const sameType = bindingTypes
1511
- // filter once to find duplicate binding types
1512
- .filter((type, i) => bindingTypes.indexOf(type) !== i)
1513
- // filter twice to only get _unique_ duplicate binding types
1514
- .filter(
1515
- (type, i, duplicateBindingTypes) =>
1516
- duplicateBindingTypes.indexOf(type) === i
1517
- );
1518
-
1519
- const differentTypes = bindingTypes.filter(
1520
- (type, i) => bindingTypes.indexOf(type) === i
1521
- );
1522
-
1523
- if (differentTypes.length > 1) {
1524
- // we have multiple different types using the same name
1525
- diagnostics.errors.push(
1526
- `${bindingName} assigned to ${ENGLISH.format(differentTypes)} bindings.`
1527
- );
1528
- }
1529
-
1530
- sameType.forEach((bindingType) => {
1531
- diagnostics.errors.push(
1532
- `${bindingName} assigned to multiple ${bindingType} bindings.`
1533
- );
1534
- });
1535
- }
1536
-
1537
- if (hasDuplicates) {
1538
- const problem =
1539
- "Bindings must have unique names, so that they can all be referenced in the worker.";
1540
- const resolution = "Please change your bindings to have unique names.";
1541
- diagnostics.errors.push(`${problem}\n${resolution}`);
1542
- }
1543
-
1544
- return !hasDuplicates;
1866
+ let hasDuplicates = false;
1867
+
1868
+ const bindingsGroupedByType = {
1869
+ "Durable Object": getBindingNames(durable_objects),
1870
+ "KV Namespace": getBindingNames(kv_namespaces),
1871
+ "R2 Bucket": getBindingNames(r2_buckets),
1872
+ "Analytics Engine Dataset": getBindingNames(analytics_engine_datasets),
1873
+ "Text Blob": getBindingNames(text_blobs),
1874
+ Unsafe: getBindingNames(unsafe),
1875
+ "Environment Variable": getBindingNames(vars),
1876
+ Definition: getBindingNames(define),
1877
+ "WASM Module": getBindingNames(wasm_modules),
1878
+ "Data Blob": getBindingNames(data_blobs),
1879
+ } as Record<string, string[]>;
1880
+
1881
+ const bindingsGroupedByName: Record<string, string[]> = {};
1882
+
1883
+ for (const bindingType in bindingsGroupedByType) {
1884
+ const bindingNames = bindingsGroupedByType[bindingType];
1885
+
1886
+ for (const bindingName of bindingNames) {
1887
+ if (!(bindingName in bindingsGroupedByName)) {
1888
+ bindingsGroupedByName[bindingName] = [];
1889
+ }
1890
+
1891
+ bindingsGroupedByName[bindingName].push(bindingType);
1892
+ }
1893
+ }
1894
+
1895
+ for (const bindingName in bindingsGroupedByName) {
1896
+ const bindingTypes = bindingsGroupedByName[bindingName];
1897
+ if (bindingTypes.length < 2) {
1898
+ // there's only one (or zero) binding(s) with this name, which is fine, actually
1899
+ continue;
1900
+ }
1901
+
1902
+ hasDuplicates = true;
1903
+
1904
+ // there's two types of duplicates we want to look for:
1905
+ // - bindings with the same name of the same type (e.g. two Durable Objects both named "OBJ")
1906
+ // - bindings with the same name of different types (a KV namespace and DO both named "DATA")
1907
+
1908
+ const sameType = bindingTypes
1909
+ // filter once to find duplicate binding types
1910
+ .filter((type, i) => bindingTypes.indexOf(type) !== i)
1911
+ // filter twice to only get _unique_ duplicate binding types
1912
+ .filter(
1913
+ (type, i, duplicateBindingTypes) =>
1914
+ duplicateBindingTypes.indexOf(type) === i
1915
+ );
1916
+
1917
+ const differentTypes = bindingTypes.filter(
1918
+ (type, i) => bindingTypes.indexOf(type) === i
1919
+ );
1920
+
1921
+ if (differentTypes.length > 1) {
1922
+ // we have multiple different types using the same name
1923
+ diagnostics.errors.push(
1924
+ `${bindingName} assigned to ${ENGLISH.format(differentTypes)} bindings.`
1925
+ );
1926
+ }
1927
+
1928
+ sameType.forEach((bindingType) => {
1929
+ diagnostics.errors.push(
1930
+ `${bindingName} assigned to multiple ${bindingType} bindings.`
1931
+ );
1932
+ });
1933
+ }
1934
+
1935
+ if (hasDuplicates) {
1936
+ const problem =
1937
+ "Bindings must have unique names, so that they can all be referenced in the worker.";
1938
+ const resolution = "Please change your bindings to have unique names.";
1939
+ diagnostics.errors.push(`${problem}\n${resolution}`);
1940
+ }
1941
+
1942
+ return !hasDuplicates;
1545
1943
  };
1944
+
1546
1945
  const validateServiceBinding: ValidatorFn = (diagnostics, field, value) => {
1547
- if (typeof value !== "object" || value === null) {
1548
- diagnostics.errors.push(
1549
- `"services" bindings should be objects, but got ${JSON.stringify(value)}`
1550
- );
1551
- return false;
1552
- }
1553
- let isValid = true;
1554
- // Service bindings must have a binding, service, and environment.
1555
- if (!isRequiredProperty(value, "binding", "string")) {
1556
- diagnostics.errors.push(
1557
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1558
- value
1559
- )}.`
1560
- );
1561
- isValid = false;
1562
- }
1563
- if (!isRequiredProperty(value, "service", "string")) {
1564
- diagnostics.errors.push(
1565
- `"${field}" bindings should have a string "service" field but got ${JSON.stringify(
1566
- value
1567
- )}.`
1568
- );
1569
- isValid = false;
1570
- }
1571
- if (!isOptionalProperty(value, "environment", "string")) {
1572
- diagnostics.errors.push(
1573
- `"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
1574
- value
1575
- )}.`
1576
- );
1577
- isValid = false;
1578
- }
1579
- return isValid;
1946
+ if (typeof value !== "object" || value === null) {
1947
+ diagnostics.errors.push(
1948
+ `"services" bindings should be objects, but got ${JSON.stringify(value)}`
1949
+ );
1950
+ return false;
1951
+ }
1952
+ let isValid = true;
1953
+ // Service bindings must have a binding, service, and environment.
1954
+ if (!isRequiredProperty(value, "binding", "string")) {
1955
+ diagnostics.errors.push(
1956
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1957
+ value
1958
+ )}.`
1959
+ );
1960
+ isValid = false;
1961
+ }
1962
+ if (!isRequiredProperty(value, "service", "string")) {
1963
+ diagnostics.errors.push(
1964
+ `"${field}" bindings should have a string "service" field but got ${JSON.stringify(
1965
+ value
1966
+ )}.`
1967
+ );
1968
+ isValid = false;
1969
+ }
1970
+ if (!isOptionalProperty(value, "environment", "string")) {
1971
+ diagnostics.errors.push(
1972
+ `"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
1973
+ value
1974
+ )}.`
1975
+ );
1976
+ isValid = false;
1977
+ }
1978
+ return isValid;
1979
+ };
1980
+
1981
+ const validateAnalyticsEngineBinding: ValidatorFn = (
1982
+ diagnostics,
1983
+ field,
1984
+ value
1985
+ ) => {
1986
+ if (typeof value !== "object" || value === null) {
1987
+ diagnostics.errors.push(
1988
+ `"analytics_engine" bindings should be objects, but got ${JSON.stringify(
1989
+ value
1990
+ )}`
1991
+ );
1992
+ return false;
1993
+ }
1994
+ let isValid = true;
1995
+ // Service bindings must have a binding and optional dataset.
1996
+ if (!isRequiredProperty(value, "binding", "string")) {
1997
+ diagnostics.errors.push(
1998
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1999
+ value
2000
+ )}.`
2001
+ );
2002
+ isValid = false;
2003
+ }
2004
+ if (
2005
+ !isOptionalProperty(value, "dataset", "string") ||
2006
+ (value as { dataset: string }).dataset?.length === 0
2007
+ ) {
2008
+ diagnostics.errors.push(
2009
+ `"${field}" bindings should, optionally, have a string "dataset" field but got ${JSON.stringify(
2010
+ value
2011
+ )}.`
2012
+ );
2013
+ isValid = false;
2014
+ }
2015
+ return isValid;
2016
+ };
2017
+
2018
+ const validateWorkerNamespaceBinding: ValidatorFn = (
2019
+ diagnostics,
2020
+ field,
2021
+ value
2022
+ ) => {
2023
+ if (typeof value !== "object" || value === null) {
2024
+ diagnostics.errors.push(
2025
+ `"${field}" binding should be objects, but got ${JSON.stringify(value)}`
2026
+ );
2027
+ return false;
2028
+ }
2029
+ let isValid = true;
2030
+ // Worker namespace bindings must have a binding, and a namespace.
2031
+ if (!isRequiredProperty(value, "binding", "string")) {
2032
+ diagnostics.errors.push(
2033
+ `"${field}" should have a string "binding" field but got ${JSON.stringify(
2034
+ value
2035
+ )}.`
2036
+ );
2037
+ isValid = false;
2038
+ }
2039
+ if (!isRequiredProperty(value, "namespace", "string")) {
2040
+ diagnostics.errors.push(
2041
+ `"${field}" should have a string "namespace" field but got ${JSON.stringify(
2042
+ value
2043
+ )}.`
2044
+ );
2045
+ isValid = false;
2046
+ }
2047
+ return isValid;
2048
+ };
2049
+
2050
+ const validateMTlsCertificateBinding: ValidatorFn = (
2051
+ diagnostics,
2052
+ field,
2053
+ value
2054
+ ) => {
2055
+ if (typeof value !== "object" || value === null) {
2056
+ diagnostics.errors.push(
2057
+ `"mtls_certificates" bindings should be objects, but got ${JSON.stringify(
2058
+ value
2059
+ )}`
2060
+ );
2061
+ return false;
2062
+ }
2063
+ let isValid = true;
2064
+ if (!isRequiredProperty(value, "binding", "string")) {
2065
+ diagnostics.errors.push(
2066
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
2067
+ value
2068
+ )}.`
2069
+ );
2070
+ isValid = false;
2071
+ }
2072
+ if (
2073
+ !isRequiredProperty(value, "certificate_id", "string") ||
2074
+ (value as { certificate_id: string }).certificate_id.length === 0
2075
+ ) {
2076
+ diagnostics.errors.push(
2077
+ `"${field}" bindings should have a string "certificate_id" field but got ${JSON.stringify(
2078
+ value
2079
+ )}.`
2080
+ );
2081
+ isValid = false;
2082
+ }
2083
+ return isValid;
2084
+ };
2085
+
2086
+ function validateQueues(envName: string): ValidatorFn {
2087
+ return (diagnostics, field, value, config) => {
2088
+ const fieldPath =
2089
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
2090
+
2091
+ if (typeof value !== "object" || Array.isArray(value) || value === null) {
2092
+ diagnostics.errors.push(
2093
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
2094
+ value
2095
+ )}.`
2096
+ );
2097
+ return false;
2098
+ }
2099
+
2100
+ let isValid = true;
2101
+ if (
2102
+ !validateAdditionalProperties(
2103
+ diagnostics,
2104
+ fieldPath,
2105
+ Object.keys(value),
2106
+ ["consumers", "producers"]
2107
+ )
2108
+ ) {
2109
+ isValid = false;
2110
+ }
2111
+
2112
+ if (hasProperty(value, "consumers")) {
2113
+ const consumers = value.consumers;
2114
+ if (!Array.isArray(consumers)) {
2115
+ diagnostics.errors.push(
2116
+ `The field "${fieldPath}.consumers" should be an array but got ${JSON.stringify(
2117
+ consumers
2118
+ )}.`
2119
+ );
2120
+ isValid = false;
2121
+ }
2122
+
2123
+ for (let i = 0; i < consumers.length; i++) {
2124
+ const consumer = consumers[i];
2125
+ const consumerPath = `${fieldPath}.consumers[${i}]`;
2126
+ if (!validateConsumer(diagnostics, consumerPath, consumer, config)) {
2127
+ isValid = false;
2128
+ }
2129
+ }
2130
+ }
2131
+
2132
+ if (hasProperty(value, "producers")) {
2133
+ if (
2134
+ !validateBindingArray(envName, validateQueueBinding)(
2135
+ diagnostics,
2136
+ `${field}.producers`,
2137
+ value.producers,
2138
+ config
2139
+ )
2140
+ ) {
2141
+ isValid = false;
2142
+ }
2143
+ }
2144
+ return isValid;
2145
+ };
2146
+ }
2147
+
2148
+ const validateConsumer: ValidatorFn = (diagnostics, field, value, _config) => {
2149
+ if (typeof value !== "object" || value === null) {
2150
+ diagnostics.errors.push(
2151
+ `"${field}" should be a objects, but got ${JSON.stringify(value)}`
2152
+ );
2153
+ return false;
2154
+ }
2155
+
2156
+ let isValid = true;
2157
+ if (
2158
+ !validateAdditionalProperties(diagnostics, field, Object.keys(value), [
2159
+ "queue",
2160
+ "max_batch_size",
2161
+ "max_batch_timeout",
2162
+ "max_retries",
2163
+ "dead_letter_queue",
2164
+ ])
2165
+ ) {
2166
+ isValid = false;
2167
+ }
2168
+
2169
+ if (!isRequiredProperty(value, "queue", "string")) {
2170
+ diagnostics.errors.push(
2171
+ `"${field}" should have a string "queue" field but got ${JSON.stringify(
2172
+ value
2173
+ )}.`
2174
+ );
2175
+ }
2176
+
2177
+ const options: {
2178
+ key: string;
2179
+ type: "number" | "string";
2180
+ }[] = [
2181
+ { key: "max_batch_size", type: "number" },
2182
+ { key: "max_batch_timeout", type: "number" },
2183
+ { key: "max_retries", type: "number" },
2184
+ { key: "dead_letter_queue", type: "string" },
2185
+ ];
2186
+ for (const optionalOpt of options) {
2187
+ if (!isOptionalProperty(value, optionalOpt.key, optionalOpt.type)) {
2188
+ diagnostics.errors.push(
2189
+ `"${field}" should, optionally, have a ${optionalOpt.type} "${
2190
+ optionalOpt.key
2191
+ }" field but got ${JSON.stringify(value)}.`
2192
+ );
2193
+ isValid = false;
2194
+ }
2195
+ }
2196
+
2197
+ return isValid;
1580
2198
  };