wrangler 0.0.0-e3a458e → 0.0.0-e3c036d7

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