wrangler 0.0.0-e3ce82b → 0.0.0-e41c7e41

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