wrangler 0.0.0-e7a0cd5b → 0.0.0-e7c7235fd

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 (268) hide show
  1. package/README.md +31 -45
  2. package/bin/wrangler.js +24 -93
  3. package/config-schema.json +3324 -0
  4. package/package.json +183 -191
  5. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  6. package/templates/__tests__/tsconfig.json +8 -0
  7. package/templates/checked-fetch.js +19 -6
  8. package/templates/facade.d.ts +19 -0
  9. package/templates/gitignore +2 -3
  10. package/templates/init-tests/test-jest-new-worker.js +3 -5
  11. package/templates/init-tests/test-vitest-new-worker.js +4 -6
  12. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  13. package/templates/middleware/common.ts +9 -4
  14. package/templates/middleware/loader-modules.ts +94 -44
  15. package/templates/middleware/loader-sw.ts +48 -32
  16. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  17. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  18. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  20. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  21. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  22. package/templates/middleware/middleware-scheduled.ts +15 -1
  23. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  24. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.ts +4 -1
  28. package/templates/pages-dev-pipeline.ts +6 -2
  29. package/templates/pages-dev-util.ts +4 -1
  30. package/templates/pages-shim.ts +1 -1
  31. package/templates/pages-template-plugin.ts +33 -14
  32. package/templates/pages-template-worker.ts +12 -3
  33. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  34. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  35. package/templates/tsconfig-sanity.ts +11 -0
  36. package/templates/tsconfig.init.json +22 -0
  37. package/templates/tsconfig.json +5 -103
  38. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  39. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  40. package/wrangler-dist/ProxyWorker.js +241 -0
  41. package/wrangler-dist/ProxyWorker.js.map +6 -0
  42. package/wrangler-dist/cli.d.ts +26345 -529
  43. package/wrangler-dist/cli.js +159104 -150579
  44. package/Cloudflare_CA.pem +0 -18
  45. package/import_meta_url.js +0 -3
  46. package/miniflare-config-stubs/.env.empty +0 -0
  47. package/miniflare-config-stubs/package.empty.json +0 -1
  48. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  49. package/miniflare-dist/index.mjs +0 -6316
  50. package/src/__tests__/access.test.ts +0 -25
  51. package/src/__tests__/api-dev.test.ts +0 -209
  52. package/src/__tests__/api-devregistry.test.js +0 -57
  53. package/src/__tests__/api.test.ts +0 -80
  54. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  55. package/src/__tests__/config-cache.test.ts +0 -42
  56. package/src/__tests__/configuration.test.ts +0 -4028
  57. package/src/__tests__/d1.test.ts +0 -72
  58. package/src/__tests__/delete.test.ts +0 -230
  59. package/src/__tests__/deployments.test.ts +0 -95
  60. package/src/__tests__/dev.test.tsx +0 -1509
  61. package/src/__tests__/dialogs.test.tsx +0 -40
  62. package/src/__tests__/generate.test.ts +0 -235
  63. package/src/__tests__/get-host-from-url.test.ts +0 -16
  64. package/src/__tests__/guess-worker-format.test.ts +0 -85
  65. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  66. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  67. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  68. package/src/__tests__/helpers/mock-bin.ts +0 -36
  69. package/src/__tests__/helpers/mock-cfetch.ts +0 -333
  70. package/src/__tests__/helpers/mock-console.ts +0 -106
  71. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  72. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  73. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  74. package/src/__tests__/helpers/mock-istty.ts +0 -74
  75. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  76. package/src/__tests__/helpers/mock-kv.ts +0 -33
  77. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -252
  78. package/src/__tests__/helpers/mock-process.ts +0 -39
  79. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  80. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  81. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  82. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -59
  83. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -104
  84. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -36
  85. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -80
  86. package/src/__tests__/helpers/msw/handlers/script.ts +0 -75
  87. package/src/__tests__/helpers/msw/handlers/user.ts +0 -63
  88. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -22
  89. package/src/__tests__/helpers/msw/index.ts +0 -21
  90. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  91. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  92. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  93. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  94. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  95. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  96. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  97. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  98. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  99. package/src/__tests__/https-options.test.ts +0 -163
  100. package/src/__tests__/index.test.ts +0 -262
  101. package/src/__tests__/init.test.ts +0 -2900
  102. package/src/__tests__/jest.setup.ts +0 -202
  103. package/src/__tests__/kv.test.ts +0 -1675
  104. package/src/__tests__/logger.test.ts +0 -141
  105. package/src/__tests__/metrics.test.ts +0 -450
  106. package/src/__tests__/middleware.scheduled.test.ts +0 -135
  107. package/src/__tests__/middleware.test.ts +0 -726
  108. package/src/__tests__/package-manager.test.ts +0 -353
  109. package/src/__tests__/pages.test.ts +0 -2223
  110. package/src/__tests__/parse.test.ts +0 -330
  111. package/src/__tests__/paths.test.ts +0 -39
  112. package/src/__tests__/publish.test.ts +0 -7660
  113. package/src/__tests__/pubsub.test.ts +0 -370
  114. package/src/__tests__/queues.test.ts +0 -371
  115. package/src/__tests__/r2.test.ts +0 -376
  116. package/src/__tests__/route.test.ts +0 -45
  117. package/src/__tests__/secret.test.ts +0 -644
  118. package/src/__tests__/tail.test.ts +0 -800
  119. package/src/__tests__/test-old-node-version.js +0 -31
  120. package/src/__tests__/type-generation.test.ts +0 -217
  121. package/src/__tests__/user.test.ts +0 -155
  122. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  123. package/src/__tests__/validate-dev-props.test.ts +0 -56
  124. package/src/__tests__/version.test.ts +0 -35
  125. package/src/__tests__/whoami.test.tsx +0 -278
  126. package/src/__tests__/worker-namespace.test.ts +0 -326
  127. package/src/abort.d.ts +0 -3
  128. package/src/api/dev.ts +0 -208
  129. package/src/api/index.ts +0 -2
  130. package/src/bundle-reporter.tsx +0 -68
  131. package/src/bundle.ts +0 -785
  132. package/src/cfetch/index.ts +0 -160
  133. package/src/cfetch/internal.ts +0 -263
  134. package/src/cli.ts +0 -28
  135. package/src/config/README.md +0 -107
  136. package/src/config/config.ts +0 -275
  137. package/src/config/diagnostics.ts +0 -80
  138. package/src/config/environment.ts +0 -563
  139. package/src/config/index.ts +0 -342
  140. package/src/config/validation-helpers.ts +0 -597
  141. package/src/config/validation.ts +0 -2113
  142. package/src/config-cache.ts +0 -85
  143. package/src/create-worker-preview.ts +0 -282
  144. package/src/create-worker-upload-form.ts +0 -321
  145. package/src/d1/backups.tsx +0 -218
  146. package/src/d1/create.tsx +0 -54
  147. package/src/d1/delete.tsx +0 -56
  148. package/src/d1/execute.tsx +0 -299
  149. package/src/d1/formatTimeAgo.ts +0 -14
  150. package/src/d1/index.ts +0 -76
  151. package/src/d1/list.tsx +0 -48
  152. package/src/d1/options.ts +0 -12
  153. package/src/d1/types.tsx +0 -14
  154. package/src/d1/utils.ts +0 -39
  155. package/src/delete.ts +0 -108
  156. package/src/deployments.ts +0 -74
  157. package/src/deprecated/index.ts +0 -438
  158. package/src/dev/dev-vars.ts +0 -39
  159. package/src/dev/dev.tsx +0 -587
  160. package/src/dev/get-local-persistence-path.tsx +0 -31
  161. package/src/dev/local.tsx +0 -717
  162. package/src/dev/remote.tsx +0 -603
  163. package/src/dev/start-server.ts +0 -513
  164. package/src/dev/use-esbuild.ts +0 -204
  165. package/src/dev/validate-dev-props.ts +0 -31
  166. package/src/dev-registry.tsx +0 -201
  167. package/src/dev.tsx +0 -869
  168. package/src/dialogs.tsx +0 -163
  169. package/src/dispatch-namespace.ts +0 -207
  170. package/src/durable.ts +0 -102
  171. package/src/entry.ts +0 -329
  172. package/src/environment-variables.ts +0 -50
  173. package/src/errors.ts +0 -11
  174. package/src/git-client.ts +0 -124
  175. package/src/global-wrangler-config-path.ts +0 -26
  176. package/src/https-options.ts +0 -127
  177. package/src/index.tsx +0 -684
  178. package/src/init.ts +0 -970
  179. package/src/inspect.ts +0 -767
  180. package/src/intl-polyfill.d.ts +0 -139
  181. package/src/is-ci.ts +0 -14
  182. package/src/is-interactive.ts +0 -16
  183. package/src/kv/helpers.ts +0 -430
  184. package/src/kv/index.ts +0 -596
  185. package/src/logger.ts +0 -92
  186. package/src/metrics/index.ts +0 -5
  187. package/src/metrics/metrics-config.ts +0 -239
  188. package/src/metrics/metrics-dispatcher.ts +0 -96
  189. package/src/metrics/metrics-usage-headers.ts +0 -24
  190. package/src/metrics/send-event.ts +0 -94
  191. package/src/miniflare-cli/README.md +0 -30
  192. package/src/miniflare-cli/assets.ts +0 -215
  193. package/src/miniflare-cli/index.ts +0 -213
  194. package/src/miniflare-cli/request-context.ts +0 -40
  195. package/src/module-collection.ts +0 -267
  196. package/src/open-in-browser.ts +0 -17
  197. package/src/package-manager.ts +0 -219
  198. package/src/pages/build.tsx +0 -238
  199. package/src/pages/constants.ts +0 -18
  200. package/src/pages/deployments.tsx +0 -106
  201. package/src/pages/dev.tsx +0 -693
  202. package/src/pages/errors.ts +0 -66
  203. package/src/pages/functions/buildPlugin.ts +0 -110
  204. package/src/pages/functions/buildWorker.ts +0 -156
  205. package/src/pages/functions/filepath-routing.test.ts +0 -234
  206. package/src/pages/functions/filepath-routing.ts +0 -189
  207. package/src/pages/functions/identifiers.ts +0 -78
  208. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  209. package/src/pages/functions/routes-consolidation.ts +0 -73
  210. package/src/pages/functions/routes-transformation.test.ts +0 -282
  211. package/src/pages/functions/routes-transformation.ts +0 -115
  212. package/src/pages/functions/routes-validation.test.ts +0 -403
  213. package/src/pages/functions/routes-validation.ts +0 -202
  214. package/src/pages/functions/routes.ts +0 -151
  215. package/src/pages/functions.tsx +0 -82
  216. package/src/pages/hash.tsx +0 -13
  217. package/src/pages/index.tsx +0 -94
  218. package/src/pages/projects.tsx +0 -169
  219. package/src/pages/publish.tsx +0 -436
  220. package/src/pages/types.ts +0 -49
  221. package/src/pages/upload.tsx +0 -425
  222. package/src/pages/utils.ts +0 -12
  223. package/src/parse.ts +0 -286
  224. package/src/paths.ts +0 -71
  225. package/src/proxy.ts +0 -689
  226. package/src/publish/index.ts +0 -270
  227. package/src/publish/publish.ts +0 -1035
  228. package/src/pubsub/index.ts +0 -286
  229. package/src/pubsub/pubsub-commands.tsx +0 -624
  230. package/src/queues/cli/commands/consumer/add.ts +0 -71
  231. package/src/queues/cli/commands/consumer/index.ts +0 -22
  232. package/src/queues/cli/commands/consumer/remove.ts +0 -38
  233. package/src/queues/cli/commands/create.ts +0 -25
  234. package/src/queues/cli/commands/delete.ts +0 -26
  235. package/src/queues/cli/commands/index.ts +0 -33
  236. package/src/queues/cli/commands/list.ts +0 -25
  237. package/src/queues/client.ts +0 -135
  238. package/src/r2/helpers.ts +0 -131
  239. package/src/r2/index.ts +0 -277
  240. package/src/routes.ts +0 -140
  241. package/src/secret/index.ts +0 -379
  242. package/src/selfsigned.d.ts +0 -29
  243. package/src/sites.tsx +0 -372
  244. package/src/tail/createTail.ts +0 -315
  245. package/src/tail/filters.ts +0 -277
  246. package/src/tail/index.ts +0 -214
  247. package/src/tail/printing.ts +0 -107
  248. package/src/type-generation.ts +0 -159
  249. package/src/update-check.ts +0 -19
  250. package/src/user/access.ts +0 -69
  251. package/src/user/choose-account.tsx +0 -69
  252. package/src/user/env-vars.ts +0 -46
  253. package/src/user/generate-auth-url.ts +0 -33
  254. package/src/user/generate-random-state.ts +0 -16
  255. package/src/user/index.ts +0 -3
  256. package/src/user/user.tsx +0 -1192
  257. package/src/utils/collectKeyValues.ts +0 -14
  258. package/src/whoami.tsx +0 -169
  259. package/src/worker.ts +0 -242
  260. package/src/yargs-types.ts +0 -20
  261. package/src/zones.ts +0 -191
  262. package/templates/d1-beta-facade.js +0 -174
  263. package/templates/experimental-local-cache-stubs.js +0 -27
  264. package/templates/first-party-worker-module-facade.ts +0 -18
  265. package/templates/format-dev-errors.ts +0 -32
  266. package/templates/serve-static-assets.ts +0 -63
  267. package/templates/service-bindings-module-facade.js +0 -54
  268. package/templates/service-bindings-sw-facade.js +0 -42
@@ -1,2113 +0,0 @@
1
- import path from "node:path";
2
- import TOML from "@iarna/toml";
3
- import { Diagnostics } from "./diagnostics";
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,
28
- } from "./validation-helpers";
29
- import type { Config, DevConfig, RawConfig, RawDevConfig } from "./config";
30
- import type {
31
- RawEnvironment,
32
- DeprecatedUpload,
33
- Environment,
34
- Rule,
35
- } from "./environment";
36
- import type { ValidatorFn } from "./validation-helpers";
37
-
38
- const ENGLISH = new Intl.ListFormat("en");
39
-
40
- /**
41
- * Validate the given `rawConfig` object that was loaded from `configPath`.
42
- *
43
- * The configuration is normalized, which includes using default values for missing field,
44
- * and copying over inheritable fields into named environments.
45
- *
46
- * Any errors or warnings from the validation are available in the returned `diagnostics` object.
47
- */
48
- export function normalizeAndValidateConfig(
49
- rawConfig: RawConfig,
50
- configPath: string | undefined,
51
- args: unknown
52
- ): {
53
- config: Config;
54
- diagnostics: Diagnostics;
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
- 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 };
240
- }
241
-
242
- /**
243
- * Validate the `build` configuration and return the normalized values.
244
- */
245
- function normalizeAndValidateBuild(
246
- diagnostics: Diagnostics,
247
- rawEnv: RawEnvironment,
248
- rawBuild: Config["build"],
249
- configPath: string | undefined
250
- ): Config["build"] & { deprecatedUpload: DeprecatedUpload } {
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
- };
332
- }
333
-
334
- /**
335
- * Validate the `main` field and return the normalized values.
336
- */
337
- function normalizeAndValidateMainField(
338
- configPath: string | undefined,
339
- rawMain: string | undefined,
340
- deprecatedUpload: DeprecatedUpload | undefined
341
- ): string | undefined {
342
- const configDir = path.dirname(configPath ?? "wrangler.toml");
343
- if (rawMain !== undefined) {
344
- if (typeof rawMain === "string") {
345
- const directory = path.resolve(configDir);
346
- return path.resolve(directory, rawMain);
347
- } else {
348
- return rawMain;
349
- }
350
- } else if (deprecatedUpload?.main !== undefined) {
351
- const directory = path.resolve(
352
- configDir,
353
- deprecatedUpload?.dir || "./dist"
354
- );
355
- return path.resolve(directory, deprecatedUpload.main);
356
- } else {
357
- return;
358
- }
359
- }
360
-
361
- /**
362
- * Validate the `dev` configuration and return the normalized values.
363
- */
364
- function normalizeAndValidateDev(
365
- diagnostics: Diagnostics,
366
- rawDev: RawDevConfig
367
- ): DevConfig {
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 };
406
- }
407
-
408
- /**
409
- * Validate the `migrations` configuration and return the normalized values.
410
- */
411
- function normalizeAndValidateMigrations(
412
- diagnostics: Diagnostics,
413
- rawMigrations: Config["migrations"],
414
- durableObjects: Config["durable_objects"]
415
- ): Config["migrations"] {
416
- if (!Array.isArray(rawMigrations)) {
417
- diagnostics.errors.push(
418
- `The optional "migrations" field should be an array, but got ${JSON.stringify(
419
- rawMigrations
420
- )}`
421
- );
422
- return [];
423
- } else {
424
- for (let i = 0; i < rawMigrations.length; i++) {
425
- const { tag, new_classes, renamed_classes, deleted_classes, ...rest } =
426
- rawMigrations[i];
427
-
428
- validateAdditionalProperties(
429
- diagnostics,
430
- "migrations",
431
- Object.keys(rest),
432
- []
433
- );
434
-
435
- validateRequiredProperty(
436
- diagnostics,
437
- `migrations[${i}]`,
438
- `tag`,
439
- tag,
440
- "string"
441
- );
442
- validateOptionalTypedArray(
443
- diagnostics,
444
- `migrations[${i}].new_classes`,
445
- new_classes,
446
- "string"
447
- );
448
- if (renamed_classes !== undefined) {
449
- if (!Array.isArray(renamed_classes)) {
450
- diagnostics.errors.push(
451
- `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
452
- renamed_classes
453
- )}.`
454
- );
455
- } else if (
456
- renamed_classes.some(
457
- (c) =>
458
- typeof c !== "object" ||
459
- !isRequiredProperty(c, "from", "string") ||
460
- !isRequiredProperty(c, "to", "string")
461
- )
462
- ) {
463
- diagnostics.errors.push(
464
- `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
465
- renamed_classes
466
- )}.`
467
- );
468
- }
469
- }
470
- validateOptionalTypedArray(
471
- diagnostics,
472
- `migrations[${i}].deleted_classes`,
473
- deleted_classes,
474
- "string"
475
- );
476
- }
477
-
478
- if (
479
- Array.isArray(durableObjects?.bindings) &&
480
- durableObjects.bindings.length > 0
481
- ) {
482
- // intrinsic [durable_objects] implies [migrations]
483
- const exportedDurableObjects = (durableObjects.bindings || []).filter(
484
- (binding) => !binding.script_name
485
- );
486
- if (exportedDurableObjects.length > 0 && rawMigrations.length === 0) {
487
- if (
488
- !exportedDurableObjects.some(
489
- (exportedDurableObject) =>
490
- typeof exportedDurableObject.class_name !== "string"
491
- )
492
- ) {
493
- const durableObjectClassnames = exportedDurableObjects.map(
494
- (durable) => durable.class_name
495
- );
496
-
497
- diagnostics.warnings.push(
498
- `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${durableObjectClassnames.join(
499
- ", "
500
- )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Add this configuration to your wrangler.toml:
501
-
502
- \`\`\`
503
- [[migrations]]
504
- tag = "v1" # Should be unique for each entry
505
- new_classes = [${durableObjectClassnames
506
- .map((name) => `"${name}"`)
507
- .join(", ")}]
508
- \`\`\`
509
-
510
- Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
511
- );
512
- }
513
- }
514
- }
515
-
516
- return rawMigrations;
517
- }
518
- }
519
-
520
- /**
521
- * Validate the `site` configuration and return the normalized values.
522
- */
523
- function normalizeAndValidateSite(
524
- diagnostics: Diagnostics,
525
- configPath: string | undefined,
526
- rawConfig: RawConfig,
527
- mainEntryPoint: string | undefined
528
- ): Config["site"] {
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
- };
673
- }
674
-
675
- /**
676
- * Map the paths of the `wasm_modules`, `text_blobs` or `data_blobs` configuration to be relative to the current working directory.
677
- */
678
- function normalizeAndValidateModulePaths(
679
- diagnostics: Diagnostics,
680
- configPath: string | undefined,
681
- field: "wasm_modules" | "text_blobs" | "data_blobs",
682
- rawMapping: Record<string, string> | undefined
683
- ): Record<string, string> | undefined {
684
- if (rawMapping === undefined) {
685
- return undefined;
686
- }
687
- const mapping: Record<string, string> = {};
688
- // Rewrite paths to be relative to the cwd, rather than the config path.
689
- for (const [name, filePath] of Object.entries(rawMapping)) {
690
- if (isString(diagnostics, `${field}['${name}']`, filePath, undefined)) {
691
- if (configPath) {
692
- mapping[name] = configPath
693
- ? path.relative(
694
- process.cwd(),
695
- path.join(path.dirname(configPath), filePath)
696
- )
697
- : filePath;
698
- }
699
- }
700
- }
701
- return mapping;
702
- }
703
-
704
- /**
705
- * Check whether a value has the shape of a route, which can be a string
706
- * or an object that looks like {pattern: string, zone_id: string }
707
- */
708
- function isValidRouteValue(item: unknown): boolean {
709
- if (!item) {
710
- return false;
711
- }
712
- if (typeof item === "string") {
713
- return true;
714
- }
715
- if (typeof item === "object") {
716
- if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
717
- return false;
718
- }
719
-
720
- const otherKeys = Object.keys(item).length - 1; // minus one to subtract "pattern"
721
-
722
- const hasZoneId =
723
- hasProperty(item, "zone_id") && typeof item.zone_id === "string";
724
- const hasZoneName =
725
- hasProperty(item, "zone_name") && typeof item.zone_name === "string";
726
- const hasCustomDomainFlag =
727
- hasProperty(item, "custom_domain") &&
728
- typeof item.custom_domain === "boolean";
729
-
730
- if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
731
- return true;
732
- } else if (
733
- otherKeys === 1 &&
734
- (hasZoneId || hasZoneName || hasCustomDomainFlag)
735
- ) {
736
- return true;
737
- }
738
- }
739
- return false;
740
- }
741
-
742
- /**
743
- * If account_id has been passed as an empty string, normalise it to undefined.
744
- * This is to workaround older 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;
778
- }
779
-
780
- /**
781
- * Validate that the field is a route.
782
- */
783
- const isRoute: ValidatorFn = (diagnostics, field, value) => {
784
- if (value !== undefined && !isValidRouteValue(value)) {
785
- diagnostics.errors.push(
786
- `Expected "${field}" to be either a string, or an object with shape { pattern, custom_domain, zone_id | zone_name }, but got ${JSON.stringify(
787
- value
788
- )}.`
789
- );
790
- return false;
791
- }
792
- return true;
793
- };
794
-
795
- /**
796
- * Validate that the field is an array of routes.
797
- */
798
- const isRouteArray: ValidatorFn = (diagnostics, field, value) => {
799
- if (value === undefined) {
800
- return true;
801
- }
802
- if (!Array.isArray(value)) {
803
- diagnostics.errors.push(
804
- `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
805
- );
806
- return false;
807
- }
808
- const invalidRoutes = [];
809
- for (const item of value) {
810
- if (!isValidRouteValue(item)) {
811
- invalidRoutes.push(item);
812
- }
813
- }
814
- if (invalidRoutes.length > 0) {
815
- diagnostics.errors.push(
816
- `Expected "${field}" to be an array of either strings or objects with the shape { pattern, custom_domain, zone_id | zone_name }, but these weren't valid: ${JSON.stringify(
817
- invalidRoutes,
818
- null,
819
- 2
820
- )}.`
821
- );
822
- }
823
- return invalidRoutes.length === 0;
824
- };
825
-
826
- function normalizeAndValidateRoute(
827
- diagnostics: Diagnostics,
828
- topLevelEnv: Environment | undefined,
829
- rawEnv: RawEnvironment
830
- ): Config["route"] {
831
- return inheritable(
832
- diagnostics,
833
- topLevelEnv,
834
- mutateEmptyStringRouteValue(diagnostics, rawEnv),
835
- "route",
836
- isRoute,
837
- undefined
838
- );
839
- }
840
-
841
- function validateRoutes(
842
- diagnostics: Diagnostics,
843
- topLevelEnv: Environment | undefined,
844
- rawEnv: RawEnvironment
845
- ): Config["routes"] {
846
- return inheritable(
847
- diagnostics,
848
- topLevelEnv,
849
- rawEnv,
850
- "routes",
851
- all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
852
- undefined
853
- );
854
- }
855
-
856
- /**
857
- * Validate top-level environment configuration and return the normalized values.
858
- */
859
- function normalizeAndValidateEnvironment(
860
- diagnostics: Diagnostics,
861
- configPath: string | undefined,
862
- topLevelEnv: RawEnvironment
863
- ): Environment;
864
- /**
865
- * Validate the named environment configuration and return the normalized values.
866
- */
867
- function normalizeAndValidateEnvironment(
868
- diagnostics: Diagnostics,
869
- configPath: string | undefined,
870
- rawEnv: RawEnvironment,
871
- envName: string,
872
- topLevelEnv: Environment,
873
- isLegacyEnv: boolean,
874
- rawConfig: RawConfig
875
- ): Environment;
876
- function normalizeAndValidateEnvironment(
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
884
- ): 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
- metadata_binding: notInheritable(
1047
- diagnostics,
1048
- topLevelEnv,
1049
- rawConfig,
1050
- rawEnv,
1051
- envName,
1052
- "metadata_binding",
1053
- isString,
1054
- undefined
1055
- ),
1056
- define: notInheritable(
1057
- diagnostics,
1058
- topLevelEnv,
1059
- rawConfig,
1060
- rawEnv,
1061
- envName,
1062
- "define",
1063
- validateDefines(envName),
1064
- {}
1065
- ),
1066
- durable_objects: notInheritable(
1067
- diagnostics,
1068
- topLevelEnv,
1069
- rawConfig,
1070
- rawEnv,
1071
- envName,
1072
- "durable_objects",
1073
- validateBindingsProperty(envName, validateDurableObjectBinding),
1074
- {
1075
- bindings: [],
1076
- }
1077
- ),
1078
- kv_namespaces: notInheritable(
1079
- diagnostics,
1080
- topLevelEnv,
1081
- rawConfig,
1082
- rawEnv,
1083
- envName,
1084
- "kv_namespaces",
1085
- validateBindingArray(envName, validateKVBinding),
1086
- []
1087
- ),
1088
- queues: notInheritable(
1089
- diagnostics,
1090
- topLevelEnv,
1091
- rawConfig,
1092
- rawEnv,
1093
- envName,
1094
- "queues",
1095
- validateQueues(envName),
1096
- { producers: [], consumers: [] }
1097
- ),
1098
- r2_buckets: notInheritable(
1099
- diagnostics,
1100
- topLevelEnv,
1101
- rawConfig,
1102
- rawEnv,
1103
- envName,
1104
- "r2_buckets",
1105
- validateBindingArray(envName, validateR2Binding),
1106
- []
1107
- ),
1108
- d1_databases: notInheritable(
1109
- diagnostics,
1110
- topLevelEnv,
1111
- rawConfig,
1112
- rawEnv,
1113
- envName,
1114
- "d1_databases",
1115
- validateBindingArray(envName, validateD1Binding),
1116
- []
1117
- ),
1118
- services: notInheritable(
1119
- diagnostics,
1120
- topLevelEnv,
1121
- rawConfig,
1122
- rawEnv,
1123
- envName,
1124
- "services",
1125
- validateBindingArray(envName, validateServiceBinding),
1126
- []
1127
- ),
1128
- dispatch_namespaces: notInheritable(
1129
- diagnostics,
1130
- topLevelEnv,
1131
- rawConfig,
1132
- rawEnv,
1133
- envName,
1134
- "dispatch_namespaces",
1135
- validateBindingArray(envName, validateWorkerNamespaceBinding),
1136
- []
1137
- ),
1138
- logfwdr: inheritable(
1139
- diagnostics,
1140
- topLevelEnv,
1141
- rawEnv,
1142
- "logfwdr",
1143
- validateBindingsProperty(envName, validateCflogfwdrBinding),
1144
- {
1145
- schema: undefined,
1146
- bindings: [],
1147
- }
1148
- ),
1149
- unsafe: notInheritable(
1150
- diagnostics,
1151
- topLevelEnv,
1152
- rawConfig,
1153
- rawEnv,
1154
- envName,
1155
- "unsafe",
1156
- validateBindingsProperty(envName, validateUnsafeBinding),
1157
- {
1158
- bindings: [],
1159
- }
1160
- ),
1161
- zone_id: rawEnv.zone_id,
1162
- no_bundle: inheritable(
1163
- diagnostics,
1164
- topLevelEnv,
1165
- rawEnv,
1166
- "no_bundle",
1167
- isBoolean,
1168
- undefined
1169
- ),
1170
- minify: inheritable(
1171
- diagnostics,
1172
- topLevelEnv,
1173
- rawEnv,
1174
- "minify",
1175
- isBoolean,
1176
- undefined
1177
- ),
1178
- node_compat: inheritable(
1179
- diagnostics,
1180
- topLevelEnv,
1181
- rawEnv,
1182
- "node_compat",
1183
- isBoolean,
1184
- undefined
1185
- ),
1186
- first_party_worker: inheritable(
1187
- diagnostics,
1188
- topLevelEnv,
1189
- rawEnv,
1190
- "first_party_worker",
1191
- isBoolean,
1192
- undefined
1193
- ),
1194
- logpush: inheritable(
1195
- diagnostics,
1196
- topLevelEnv,
1197
- rawEnv,
1198
- "logpush",
1199
- isBoolean,
1200
- undefined
1201
- ),
1202
- };
1203
-
1204
- return environment;
1205
- }
1206
-
1207
- function validateAndNormalizeTsconfig(
1208
- diagnostics: Diagnostics,
1209
- topLevelEnv: Environment | undefined,
1210
- rawEnv: RawEnvironment,
1211
- configPath: string | undefined
1212
- ) {
1213
- const tsconfig = inheritable(
1214
- diagnostics,
1215
- topLevelEnv,
1216
- rawEnv,
1217
- "tsconfig",
1218
- isString,
1219
- undefined
1220
- );
1221
-
1222
- return configPath && tsconfig
1223
- ? path.relative(
1224
- process.cwd(),
1225
- path.join(path.dirname(configPath), tsconfig)
1226
- )
1227
- : tsconfig;
1228
- }
1229
-
1230
- const validateAndNormalizeRules = (
1231
- diagnostics: Diagnostics,
1232
- topLevelEnv: Environment | undefined,
1233
- rawEnv: RawEnvironment,
1234
- deprecatedRules: Rule[] | undefined,
1235
- envName: string
1236
- ): Rule[] => {
1237
- if (topLevelEnv === undefined) {
1238
- // Only create errors/warnings for the top-level environment
1239
- if (rawEnv.rules && deprecatedRules) {
1240
- diagnostics.errors.push(
1241
- `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
1242
- );
1243
- } else if (deprecatedRules) {
1244
- diagnostics.warnings.push(
1245
- `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` +
1246
- "```\n" +
1247
- TOML.stringify({ rules: deprecatedRules }) +
1248
- "```"
1249
- );
1250
- }
1251
- }
1252
-
1253
- return inheritable(
1254
- diagnostics,
1255
- topLevelEnv,
1256
- rawEnv,
1257
- "rules",
1258
- validateRules(envName),
1259
- deprecatedRules ?? []
1260
- );
1261
- };
1262
-
1263
- const validateRules =
1264
- (envName: string): ValidatorFn =>
1265
- (diagnostics, field, envValue, config) => {
1266
- if (!envValue) {
1267
- return true;
1268
- }
1269
- const fieldPath =
1270
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1271
- if (!Array.isArray(envValue)) {
1272
- diagnostics.errors.push(
1273
- `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1274
- envValue
1275
- )}.`
1276
- );
1277
- return false;
1278
- }
1279
-
1280
- let isValid = true;
1281
- for (let i = 0; i < envValue.length; i++) {
1282
- isValid =
1283
- validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) &&
1284
- isValid;
1285
- }
1286
- return isValid;
1287
- };
1288
-
1289
- const validateRule: ValidatorFn = (diagnostics, field, value) => {
1290
- if (typeof value !== "object" || value === null) {
1291
- diagnostics.errors.push(
1292
- `"${field}" should be an object but got ${JSON.stringify(value)}.`
1293
- );
1294
- return false;
1295
- }
1296
- // Rules must have a type string and glob string array, and optionally a fallthrough boolean.
1297
- let isValid = true;
1298
- const rule = value as Rule;
1299
-
1300
- if (
1301
- !isRequiredProperty(rule, "type", "string", [
1302
- "ESModule",
1303
- "CommonJS",
1304
- "CompiledWasm",
1305
- "Text",
1306
- "Data",
1307
- ])
1308
- ) {
1309
- diagnostics.errors.push(
1310
- `bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
1311
- );
1312
- isValid = false;
1313
- }
1314
-
1315
- isValid =
1316
- validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") &&
1317
- isValid;
1318
-
1319
- if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
1320
- diagnostics.errors.push(
1321
- `the field "fallthrough", when present, should be a boolean.`
1322
- );
1323
- isValid = false;
1324
- }
1325
-
1326
- return isValid;
1327
- };
1328
-
1329
- const validateDefines =
1330
- (envName: string): ValidatorFn =>
1331
- (diagnostics, field, value, config) => {
1332
- let isValid = true;
1333
- const fieldPath =
1334
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1335
-
1336
- if (typeof value === "object" && value !== null) {
1337
- for (const varName in value) {
1338
- // some casting here to appease typescript
1339
- // even though the value might not match the type
1340
- if (typeof (value as Record<string, string>)[varName] !== "string") {
1341
- diagnostics.errors.push(
1342
- `The field "${fieldPath}.${varName}" should be a string but got ${JSON.stringify(
1343
- (value as Record<string, string>)[varName]
1344
- )}.`
1345
- );
1346
- isValid = false;
1347
- }
1348
- }
1349
- } else {
1350
- if (value !== undefined) {
1351
- diagnostics.errors.push(
1352
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1353
- value
1354
- )}.\n`
1355
- );
1356
- isValid = false;
1357
- }
1358
- }
1359
-
1360
- const configDefines = Object.keys(config?.define ?? {});
1361
-
1362
- // If there are no top level vars then there is nothing to do here.
1363
- if (configDefines.length > 0) {
1364
- if (typeof value === "object" && value !== null) {
1365
- const configEnvDefines = config === undefined ? [] : Object.keys(value);
1366
-
1367
- for (const varName of configDefines) {
1368
- if (!(varName in value)) {
1369
- diagnostics.warnings.push(
1370
- `"define.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
1371
- `This is not what you probably want, since "define" configuration is not inherited by environments.\n` +
1372
- `Please add "define.${varName}" to "env.${envName}".`
1373
- );
1374
- }
1375
- }
1376
- for (const varName of configEnvDefines) {
1377
- if (!configDefines.includes(varName)) {
1378
- diagnostics.warnings.push(
1379
- `"${varName}" exists on "env.${envName}", but not on the top level.\n` +
1380
- `This is not what you probably want, since "define" configuration within environments can only override existing top level "define" configuration\n` +
1381
- `Please remove "${fieldPath}.${varName}", or add "define.${varName}".`
1382
- );
1383
- }
1384
- }
1385
- }
1386
- }
1387
-
1388
- return isValid;
1389
- };
1390
-
1391
- const validateVars =
1392
- (envName: string): ValidatorFn =>
1393
- (diagnostics, field, value, config) => {
1394
- let isValid = true;
1395
- const fieldPath =
1396
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1397
- const configVars = Object.keys(config?.vars ?? {});
1398
- // If there are no top level vars then there is nothing to do here.
1399
- if (configVars.length > 0) {
1400
- if (typeof value !== "object" || value === null) {
1401
- diagnostics.errors.push(
1402
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1403
- value
1404
- )}.\n`
1405
- );
1406
- isValid = false;
1407
- } else {
1408
- for (const varName of configVars) {
1409
- if (!(varName in value)) {
1410
- diagnostics.warnings.push(
1411
- `"vars.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
1412
- `This is not what you probably want, since "vars" configuration is not inherited by environments.\n` +
1413
- `Please add "vars.${varName}" to "env.${envName}".`
1414
- );
1415
- }
1416
- }
1417
- }
1418
- }
1419
- return isValid;
1420
- };
1421
-
1422
- const validateBindingsProperty =
1423
- (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1424
- (diagnostics, field, value, config) => {
1425
- let isValid = true;
1426
- const fieldPath =
1427
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1428
-
1429
- if (value !== undefined) {
1430
- // Check the validity of the `value` as a bindings container.
1431
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
1432
- diagnostics.errors.push(
1433
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1434
- value
1435
- )}.`
1436
- );
1437
- isValid = false;
1438
- } else if (!hasProperty(value, "bindings")) {
1439
- diagnostics.errors.push(
1440
- `The field "${fieldPath}" is missing the required "bindings" property.`
1441
- );
1442
- isValid = false;
1443
- } else if (!Array.isArray(value.bindings)) {
1444
- diagnostics.errors.push(
1445
- `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
1446
- value.bindings
1447
- )}.`
1448
- );
1449
- isValid = false;
1450
- } else {
1451
- for (let i = 0; i < value.bindings.length; i++) {
1452
- const binding = value.bindings[i];
1453
- const bindingDiagnostics = new Diagnostics(
1454
- `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
1455
- );
1456
- isValid =
1457
- validateBinding(
1458
- bindingDiagnostics,
1459
- `${fieldPath}.bindings[${i}]`,
1460
- binding,
1461
- config
1462
- ) && isValid;
1463
- diagnostics.addChild(bindingDiagnostics);
1464
- }
1465
- }
1466
-
1467
- const configBindingNames = getBindingNames(
1468
- config?.[field as keyof Environment]
1469
- );
1470
- if (isValid && configBindingNames.length > 0) {
1471
- // If there are top level bindings then check that they all appear in the environment.
1472
- const envBindingNames = new Set(getBindingNames(value));
1473
- const missingBindings = configBindingNames.filter(
1474
- (name) => !envBindingNames.has(name)
1475
- );
1476
- if (missingBindings.length > 0) {
1477
- diagnostics.warnings.push(
1478
- `The following bindings are at the top level, but not on "env.${envName}".\n` +
1479
- `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1480
- `Please add a binding for each to "${fieldPath}.bindings":\n` +
1481
- missingBindings.map((name) => `- ${name}`).join("\n")
1482
- );
1483
- }
1484
- }
1485
- }
1486
- return isValid;
1487
- };
1488
-
1489
- /**
1490
- * Check that the given field is a valid "durable_object" binding object.
1491
- */
1492
- const validateDurableObjectBinding: ValidatorFn = (
1493
- diagnostics,
1494
- field,
1495
- value
1496
- ) => {
1497
- if (typeof value !== "object" || value === null) {
1498
- diagnostics.errors.push(
1499
- `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
1500
- );
1501
- return false;
1502
- }
1503
-
1504
- // Durable Object bindings must have a name and class_name, and optionally a script_name and an environment.
1505
- let isValid = true;
1506
- if (!isRequiredProperty(value, "name", "string")) {
1507
- diagnostics.errors.push(`binding should have a string "name" field.`);
1508
- isValid = false;
1509
- }
1510
- if (!isRequiredProperty(value, "class_name", "string")) {
1511
- diagnostics.errors.push(`binding should have a string "class_name" field.`);
1512
- isValid = false;
1513
- }
1514
- if (!isOptionalProperty(value, "script_name", "string")) {
1515
- diagnostics.errors.push(
1516
- `the field "script_name", when present, should be a string.`
1517
- );
1518
- isValid = false;
1519
- }
1520
- // environment requires a script_name
1521
- if (!isOptionalProperty(value, "environment", "string")) {
1522
- diagnostics.errors.push(
1523
- `the field "environment", when present, should be a string.`
1524
- );
1525
- isValid = false;
1526
- }
1527
-
1528
- if ("environment" in value && !("script_name" in value)) {
1529
- diagnostics.errors.push(
1530
- `binding should have a "script_name" field if "environment" is present.`
1531
- );
1532
- isValid = false;
1533
- }
1534
-
1535
- return isValid;
1536
- };
1537
-
1538
- const validateCflogfwdrBinding: ValidatorFn = (diagnostics, field, value) => {
1539
- if (typeof value !== "object" || value === null) {
1540
- diagnostics.errors.push(
1541
- `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
1542
- );
1543
- return false;
1544
- }
1545
-
1546
- let isValid = true;
1547
- if (!isRequiredProperty(value, "name", "string")) {
1548
- diagnostics.errors.push(`binding should have a string "name" field.`);
1549
- isValid = false;
1550
- }
1551
-
1552
- if (!isRequiredProperty(value, "destination", "string")) {
1553
- diagnostics.errors.push(
1554
- `binding should have a string "destination" field.`
1555
- );
1556
- isValid = false;
1557
- }
1558
-
1559
- return isValid;
1560
- };
1561
-
1562
- /**
1563
- * Check that the given field is a valid "unsafe" binding object.
1564
- *
1565
- * TODO: further validation of known unsafe bindings.
1566
- */
1567
- const validateUnsafeBinding: ValidatorFn = (diagnostics, field, value) => {
1568
- if (typeof value !== "object" || value === null) {
1569
- diagnostics.errors.push(
1570
- `Expected ${field} to be an object but got ${JSON.stringify(value)}.`
1571
- );
1572
- return false;
1573
- }
1574
-
1575
- let isValid = true;
1576
- // Unsafe bindings must have a name and type.
1577
- if (!isRequiredProperty(value, "name", "string")) {
1578
- diagnostics.errors.push(`binding should have a string "name" field.`);
1579
- isValid = false;
1580
- }
1581
- if (isRequiredProperty(value, "type", "string")) {
1582
- const safeBindings = [
1583
- "plain_text",
1584
- "json",
1585
- "wasm_module",
1586
- "data_blob",
1587
- "text_blob",
1588
- "kv_namespace",
1589
- "durable_object_namespace",
1590
- "d1_database",
1591
- "r2_bucket",
1592
- "service",
1593
- "logfwdr",
1594
- ];
1595
-
1596
- if (safeBindings.includes(value.type)) {
1597
- diagnostics.warnings.push(
1598
- `The binding type "${value.type}" is directly supported by wrangler.\n` +
1599
- `Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.\n` +
1600
- "For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration"
1601
- );
1602
- }
1603
- } else {
1604
- diagnostics.errors.push(`binding should have a string "type" field.`);
1605
- isValid = false;
1606
- }
1607
- return isValid;
1608
- };
1609
-
1610
- /**
1611
- * Check that the given environment field is a valid array of bindings.
1612
- */
1613
- const validateBindingArray =
1614
- (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1615
- (diagnostics, field, envValue, config) => {
1616
- if (envValue === undefined) {
1617
- return true;
1618
- }
1619
-
1620
- const fieldPath =
1621
- config === undefined ? `${field}` : `env.${envName}.${field}`;
1622
- if (!Array.isArray(envValue)) {
1623
- diagnostics.errors.push(
1624
- `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1625
- envValue
1626
- )}.`
1627
- );
1628
- return false;
1629
- }
1630
-
1631
- let isValid = true;
1632
- for (let i = 0; i < envValue.length; i++) {
1633
- isValid =
1634
- validateBinding(
1635
- diagnostics,
1636
- `${fieldPath}[${i}]`,
1637
- envValue[i],
1638
- config
1639
- ) && isValid;
1640
- }
1641
- const configValue = config?.[field as keyof Environment] as {
1642
- binding: unknown;
1643
- }[];
1644
- if (Array.isArray(configValue)) {
1645
- const configBindingNames = configValue.map((value) => value.binding);
1646
- // If there are no top level bindings then there is nothing to do here.
1647
- if (configBindingNames.length > 0) {
1648
- const envBindingNames = new Set(envValue.map((value) => value.binding));
1649
- for (const configBindingName of configBindingNames) {
1650
- if (!envBindingNames.has(configBindingName)) {
1651
- diagnostics.warnings.push(
1652
- `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".\n` +
1653
- `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1654
- `Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
1655
- );
1656
- }
1657
- }
1658
- }
1659
- }
1660
- return isValid;
1661
- };
1662
-
1663
- const validateKVBinding: ValidatorFn = (diagnostics, field, value) => {
1664
- if (typeof value !== "object" || value === null) {
1665
- diagnostics.errors.push(
1666
- `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
1667
- value
1668
- )}`
1669
- );
1670
- return false;
1671
- }
1672
- let isValid = true;
1673
- // KV bindings must have a binding and id.
1674
- if (!isRequiredProperty(value, "binding", "string")) {
1675
- diagnostics.errors.push(
1676
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1677
- value
1678
- )}.`
1679
- );
1680
- isValid = false;
1681
- }
1682
- if (
1683
- !isRequiredProperty(value, "id", "string") ||
1684
- (value as { id: string }).id.length === 0
1685
- ) {
1686
- diagnostics.errors.push(
1687
- `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
1688
- value
1689
- )}.`
1690
- );
1691
- isValid = false;
1692
- }
1693
- if (!isOptionalProperty(value, "preview_id", "string")) {
1694
- diagnostics.errors.push(
1695
- `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
1696
- value
1697
- )}.`
1698
- );
1699
- isValid = false;
1700
- }
1701
- return isValid;
1702
- };
1703
-
1704
- const validateQueueBinding: ValidatorFn = (diagnostics, field, value) => {
1705
- if (typeof value !== "object" || value === null) {
1706
- diagnostics.errors.push(
1707
- `"queue" bindings should be objects, but got ${JSON.stringify(value)}`
1708
- );
1709
- return false;
1710
- }
1711
-
1712
- if (
1713
- !validateAdditionalProperties(diagnostics, field, Object.keys(value), [
1714
- "binding",
1715
- "queue",
1716
- ])
1717
- ) {
1718
- return false;
1719
- }
1720
-
1721
- // Queue bindings must have a binding and queue.
1722
- let isValid = true;
1723
- if (!isRequiredProperty(value, "binding", "string")) {
1724
- diagnostics.errors.push(
1725
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1726
- value
1727
- )}.`
1728
- );
1729
- isValid = false;
1730
- }
1731
- if (
1732
- !isRequiredProperty(value, "queue", "string") ||
1733
- (value as { queue: string }).queue.length === 0
1734
- ) {
1735
- diagnostics.errors.push(
1736
- `"${field}" bindings should have a string "queue" field but got ${JSON.stringify(
1737
- value
1738
- )}.`
1739
- );
1740
- isValid = false;
1741
- }
1742
- return isValid;
1743
- };
1744
-
1745
- const validateR2Binding: ValidatorFn = (diagnostics, field, value) => {
1746
- if (typeof value !== "object" || value === null) {
1747
- diagnostics.errors.push(
1748
- `"r2_buckets" bindings should be objects, but got ${JSON.stringify(
1749
- value
1750
- )}`
1751
- );
1752
- return false;
1753
- }
1754
- let isValid = true;
1755
- // R2 bindings must have a binding and bucket_name.
1756
- if (!isRequiredProperty(value, "binding", "string")) {
1757
- diagnostics.errors.push(
1758
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1759
- value
1760
- )}.`
1761
- );
1762
- isValid = false;
1763
- }
1764
- if (
1765
- !isRequiredProperty(value, "bucket_name", "string") ||
1766
- (value as { bucket_name: string }).bucket_name.length === 0
1767
- ) {
1768
- diagnostics.errors.push(
1769
- `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
1770
- value
1771
- )}.`
1772
- );
1773
- isValid = false;
1774
- }
1775
- if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
1776
- diagnostics.errors.push(
1777
- `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
1778
- value
1779
- )}.`
1780
- );
1781
- isValid = false;
1782
- }
1783
- return isValid;
1784
- };
1785
-
1786
- const validateD1Binding: ValidatorFn = (diagnostics, field, value) => {
1787
- if (typeof value !== "object" || value === null) {
1788
- diagnostics.errors.push(
1789
- `"d1_databases" bindings should be objects, but got ${JSON.stringify(
1790
- value
1791
- )}`
1792
- );
1793
- return false;
1794
- }
1795
- let isValid = true;
1796
- // D1 databases must have a binding and either a database_name or database_id.
1797
- if (!isRequiredProperty(value, "binding", "string")) {
1798
- diagnostics.errors.push(
1799
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1800
- value
1801
- )}.`
1802
- );
1803
- isValid = false;
1804
- }
1805
- if (
1806
- // TODO: allow name only, where we look up the ID dynamically
1807
- // !isOptionalProperty(value, "database_name", "string") &&
1808
- !isRequiredProperty(value, "database_id", "string")
1809
- ) {
1810
- diagnostics.errors.push(
1811
- `"${field}" bindings must have a "database_id" field but got ${JSON.stringify(
1812
- value
1813
- )}.`
1814
- );
1815
- isValid = false;
1816
- }
1817
- if (!isOptionalProperty(value, "preview_database_id", "string")) {
1818
- diagnostics.errors.push(
1819
- `"${field}" bindings should, optionally, have a string "preview_database_id" field but got ${JSON.stringify(
1820
- value
1821
- )}.`
1822
- );
1823
- isValid = false;
1824
- }
1825
- if (isValid && !process.env.NO_D1_WARNING) {
1826
- diagnostics.warnings.push(
1827
- `D1 Bindings are currently in beta 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`
1828
- );
1829
- }
1830
- return isValid;
1831
- };
1832
-
1833
- /**
1834
- * Check that bindings whose names might conflict, don't.
1835
- *
1836
- * We don't want to have, for example, a KV namespace named "DATA"
1837
- * and a Durable Object also named "DATA". Then it would be ambiguous
1838
- * what exactly would live at `env.DATA` (or in the case of service-workers,
1839
- * the `DATA` global).
1840
- */
1841
- const validateBindingsHaveUniqueNames = (
1842
- diagnostics: Diagnostics,
1843
- {
1844
- durable_objects,
1845
- kv_namespaces,
1846
- r2_buckets,
1847
- text_blobs,
1848
- unsafe,
1849
- vars,
1850
- define,
1851
- wasm_modules,
1852
- data_blobs,
1853
- }: Partial<Config>
1854
- ): boolean => {
1855
- let hasDuplicates = false;
1856
-
1857
- const bindingsGroupedByType = {
1858
- "Durable Object": getBindingNames(durable_objects),
1859
- "KV Namespace": getBindingNames(kv_namespaces),
1860
- "R2 Bucket": getBindingNames(r2_buckets),
1861
- "Text Blob": getBindingNames(text_blobs),
1862
- Unsafe: getBindingNames(unsafe),
1863
- "Environment Variable": getBindingNames(vars),
1864
- Definition: getBindingNames(define),
1865
- "WASM Module": getBindingNames(wasm_modules),
1866
- "Data Blob": getBindingNames(data_blobs),
1867
- } as Record<string, string[]>;
1868
-
1869
- const bindingsGroupedByName: Record<string, string[]> = {};
1870
-
1871
- for (const bindingType in bindingsGroupedByType) {
1872
- const bindingNames = bindingsGroupedByType[bindingType];
1873
-
1874
- for (const bindingName of bindingNames) {
1875
- if (!(bindingName in bindingsGroupedByName)) {
1876
- bindingsGroupedByName[bindingName] = [];
1877
- }
1878
-
1879
- bindingsGroupedByName[bindingName].push(bindingType);
1880
- }
1881
- }
1882
-
1883
- for (const bindingName in bindingsGroupedByName) {
1884
- const bindingTypes = bindingsGroupedByName[bindingName];
1885
- if (bindingTypes.length < 2) {
1886
- // there's only one (or zero) binding(s) with this name, which is fine, actually
1887
- continue;
1888
- }
1889
-
1890
- hasDuplicates = true;
1891
-
1892
- // there's two types of duplicates we want to look for:
1893
- // - bindings with the same name of the same type (e.g. two Durable Objects both named "OBJ")
1894
- // - bindings with the same name of different types (a KV namespace and DO both named "DATA")
1895
-
1896
- const sameType = bindingTypes
1897
- // filter once to find duplicate binding types
1898
- .filter((type, i) => bindingTypes.indexOf(type) !== i)
1899
- // filter twice to only get _unique_ duplicate binding types
1900
- .filter(
1901
- (type, i, duplicateBindingTypes) =>
1902
- duplicateBindingTypes.indexOf(type) === i
1903
- );
1904
-
1905
- const differentTypes = bindingTypes.filter(
1906
- (type, i) => bindingTypes.indexOf(type) === i
1907
- );
1908
-
1909
- if (differentTypes.length > 1) {
1910
- // we have multiple different types using the same name
1911
- diagnostics.errors.push(
1912
- `${bindingName} assigned to ${ENGLISH.format(differentTypes)} bindings.`
1913
- );
1914
- }
1915
-
1916
- sameType.forEach((bindingType) => {
1917
- diagnostics.errors.push(
1918
- `${bindingName} assigned to multiple ${bindingType} bindings.`
1919
- );
1920
- });
1921
- }
1922
-
1923
- if (hasDuplicates) {
1924
- const problem =
1925
- "Bindings must have unique names, so that they can all be referenced in the worker.";
1926
- const resolution = "Please change your bindings to have unique names.";
1927
- diagnostics.errors.push(`${problem}\n${resolution}`);
1928
- }
1929
-
1930
- return !hasDuplicates;
1931
- };
1932
-
1933
- const validateServiceBinding: ValidatorFn = (diagnostics, field, value) => {
1934
- if (typeof value !== "object" || value === null) {
1935
- diagnostics.errors.push(
1936
- `"services" bindings should be objects, but got ${JSON.stringify(value)}`
1937
- );
1938
- return false;
1939
- }
1940
- let isValid = true;
1941
- // Service bindings must have a binding, service, and environment.
1942
- if (!isRequiredProperty(value, "binding", "string")) {
1943
- diagnostics.errors.push(
1944
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1945
- value
1946
- )}.`
1947
- );
1948
- isValid = false;
1949
- }
1950
- if (!isRequiredProperty(value, "service", "string")) {
1951
- diagnostics.errors.push(
1952
- `"${field}" bindings should have a string "service" field but got ${JSON.stringify(
1953
- value
1954
- )}.`
1955
- );
1956
- isValid = false;
1957
- }
1958
- if (!isOptionalProperty(value, "environment", "string")) {
1959
- diagnostics.errors.push(
1960
- `"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
1961
- value
1962
- )}.`
1963
- );
1964
- isValid = false;
1965
- }
1966
- return isValid;
1967
- };
1968
-
1969
- const validateWorkerNamespaceBinding: ValidatorFn = (
1970
- diagnostics,
1971
- field,
1972
- value
1973
- ) => {
1974
- if (typeof value !== "object" || value === null) {
1975
- diagnostics.errors.push(
1976
- `"${field}" binding should be objects, but got ${JSON.stringify(value)}`
1977
- );
1978
- return false;
1979
- }
1980
- let isValid = true;
1981
- // Worker namespace bindings must have a binding, and a namespace.
1982
- if (!isRequiredProperty(value, "binding", "string")) {
1983
- diagnostics.errors.push(
1984
- `"${field}" should have a string "binding" field but got ${JSON.stringify(
1985
- value
1986
- )}.`
1987
- );
1988
- isValid = false;
1989
- }
1990
- if (!isRequiredProperty(value, "namespace", "string")) {
1991
- diagnostics.errors.push(
1992
- `"${field}" should have a string "namespace" field but got ${JSON.stringify(
1993
- value
1994
- )}.`
1995
- );
1996
- isValid = false;
1997
- }
1998
- return isValid;
1999
- };
2000
-
2001
- function validateQueues(envName: string): ValidatorFn {
2002
- return (diagnostics, field, value, config) => {
2003
- const fieldPath =
2004
- config === undefined ? `${field}` : `env.${envName}.${field}`;
2005
-
2006
- if (typeof value !== "object" || Array.isArray(value) || value === null) {
2007
- diagnostics.errors.push(
2008
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
2009
- value
2010
- )}.`
2011
- );
2012
- return false;
2013
- }
2014
-
2015
- let isValid = true;
2016
- if (
2017
- !validateAdditionalProperties(
2018
- diagnostics,
2019
- fieldPath,
2020
- Object.keys(value),
2021
- ["consumers", "producers"]
2022
- )
2023
- ) {
2024
- isValid = false;
2025
- }
2026
-
2027
- if (hasProperty(value, "consumers")) {
2028
- const consumers = value.consumers;
2029
- if (!Array.isArray(consumers)) {
2030
- diagnostics.errors.push(
2031
- `The field "${fieldPath}.consumers" should be an array but got ${JSON.stringify(
2032
- consumers
2033
- )}.`
2034
- );
2035
- isValid = false;
2036
- }
2037
-
2038
- for (let i = 0; i < consumers.length; i++) {
2039
- const consumer = consumers[i];
2040
- const consumerPath = `${fieldPath}.consumers[${i}]`;
2041
- if (!validateConsumer(diagnostics, consumerPath, consumer, config)) {
2042
- isValid = false;
2043
- }
2044
- }
2045
- }
2046
-
2047
- if (hasProperty(value, "producers")) {
2048
- if (
2049
- !validateBindingArray(envName, validateQueueBinding)(
2050
- diagnostics,
2051
- `${field}.producers`,
2052
- value.producers,
2053
- config
2054
- )
2055
- ) {
2056
- isValid = false;
2057
- }
2058
- }
2059
- return isValid;
2060
- };
2061
- }
2062
-
2063
- const validateConsumer: ValidatorFn = (diagnostics, field, value, _config) => {
2064
- if (typeof value !== "object" || value === null) {
2065
- diagnostics.errors.push(
2066
- `"${field}" should be a objects, but got ${JSON.stringify(value)}`
2067
- );
2068
- return false;
2069
- }
2070
-
2071
- let isValid = true;
2072
- if (
2073
- !validateAdditionalProperties(diagnostics, field, Object.keys(value), [
2074
- "queue",
2075
- "max_batch_size",
2076
- "max_batch_timeout",
2077
- "max_retries",
2078
- "dead_letter_queue",
2079
- ])
2080
- ) {
2081
- isValid = false;
2082
- }
2083
-
2084
- if (!isRequiredProperty(value, "queue", "string")) {
2085
- diagnostics.errors.push(
2086
- `"${field}" should have a string "queue" field but got ${JSON.stringify(
2087
- value
2088
- )}.`
2089
- );
2090
- }
2091
-
2092
- const options: {
2093
- key: string;
2094
- type: "number" | "string";
2095
- }[] = [
2096
- { key: "max_batch_size", type: "number" },
2097
- { key: "max_batch_timeout", type: "number" },
2098
- { key: "max_retries", type: "number" },
2099
- { key: "dead_letter_queue", type: "string" },
2100
- ];
2101
- for (const optionalOpt of options) {
2102
- if (!isOptionalProperty(value, optionalOpt.key, optionalOpt.type)) {
2103
- diagnostics.errors.push(
2104
- `"${field}" should, optionally, have a ${optionalOpt.type} "${
2105
- optionalOpt.key
2106
- }" field but got ${JSON.stringify(value)}.`
2107
- );
2108
- isValid = false;
2109
- }
2110
- }
2111
-
2112
- return isValid;
2113
- };