wrangler 0.0.0-e452a35 → 0.0.0-e464fcdb

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